package com.ruoyi.feike.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.TextStyle;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.stream.CollectorUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.controller.PdfController;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.domain.vo.BasicInformationVO;
import com.ruoyi.feike.domain.vo.ContractRecord;
import com.ruoyi.feike.mapper.*;
import com.ruoyi.feike.service.*;
import com.ruoyi.system.mapper.SysDictDataMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.security.x509.SerialNumber;

/**
 * feikeService业务层处理
 *
 * @author zmh
 * @date 2022-07-05
 */
@Service
public class BasicInformationServiceImpl implements IBasicInformationService {
    @Autowired
    private BasicInformationMapper basicInformationMapper;
    @Autowired
    private ApprovedLimitAndConditionMapper approvedLimitAndConditionMapper;
    @Autowired
    private ProposalByCommericalAndMarketingMapper proposalByCommericalAndMarketingMapper;
    @Autowired
    private IBasicContractService basicContractService;
    @Autowired
    private IDealerSectorLimitflagService dealerSectorLimitflagService;
    @Autowired
    private IDealerSectorContractgroupService dealerSectorContractgroupService;
    @Autowired
    private IGuaranteeInformationService guaranteeInformationService;
    @Autowired
    private ICreditConditionService creditConditionService;
    @Autowired
    private IWholesalePerformanceCurrentlyService wholesalePerformanceCurrentlyService;
    @Autowired
    private IDealercodeContractService dealercodeContractService;
    @Autowired
    private PdfController pdfController;
    @Autowired
    private IDealercodeCountService dealercodeCountService;
    @Autowired
    private IBasicInformationService basicInformationService;
    @Autowired
    private DealercodeContractMapper dealercodeContractMapper;
    @Autowired
    private SecuritiesMapper securitiesMapper;
    @Autowired
    private  DealercodeContractFilingMapper dealercodeContractFilingMapper;
    @Autowired
    private DealerInformationMapper dealerInformationMapper;
    @Autowired
    private IDealerInformationService dealerInformationService;
    @Autowired
    private DealerSectorContractgroupMapper dealerSectorContractgroupMapper;

    @Autowired
    private  AnnualReviewyMapper  annualReviewyMapper;

    @Autowired
    private IContractRecordSerivce  contractRecordSerivce;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private CreditConditionMapper creditConditionMapper;

    @Autowired
    private DealerSectorLimitflagMapper dealerSectorLimitflagMapper;

    @Autowired
    private HChangeLegalPersonMapper changeLegalPersonMapper;

    @Autowired
    private IAnnualReviewyService annualReviewyService;

    /**
     * 查询feike
     *
     * @param id feikeID
     * @return feike
     */
    @Override
    public BasicInformation selectBasicInformationById(String id) {
        return basicInformationMapper.selectBasicInformationById(id);
    }

    /**
     * 查询feike列表
     *
     * @param basicInformation feike
     * @return feike
     */
    @Override
    public List<BasicInformation> selectBasicInformationList(BasicInformation basicInformation) {
        return basicInformationMapper.selectBasicInformationList(basicInformation);
    }

    /**
     * 新增feike
     *
     * @param basicInformation feike
     * @return 结果
     */
    @Override
    public int insertBasicInformation(BasicInformation basicInformation) {
        return basicInformationMapper.insertBasicInformation(basicInformation);
    }

    @Override
    public int insertBasicInformationByDto(BasicInformationDTO basicInformation) {
        return basicInformationMapper.insertBasicInformationByDto(basicInformation);
    }


    /**
     * 修改feike
     *
     * @param basicInformation feike
     * @return 结果
     */
    @Override
    public int updateBasicInformation(BasicInformation basicInformation) {
        return basicInformationMapper.updateBasicInformation(basicInformation);
    }

    /**
     * 批量删除feike
     *
     * @param ids 需要删除的feikeID
     * @return 结果
     */
    @Override
    public int deleteBasicInformationByIds(String[] ids) {
        return basicInformationMapper.deleteBasicInformationByIds(ids);
    }

    /**
     * 删除feike信息
     *
     * @param id feikeID
     * @return 结果
     */
    @Override
    public int deleteBasicInformationById(String id) {
        return basicInformationMapper.deleteBasicInformationById(id);
    }

    /**
     * 根据合同规则修改相应的PriorityID字段
     *
     * @param resultMap
     * @return 结果
     */
    @Override
    public int updateBasicInformationRules(Map<String, Object> resultMap) {
        List<BasicInformationVO> basicInformations = JSONObject.parseArray(JSON.toJSONString(resultMap.get("priority")), BasicInformationVO.class);
        for (BasicInformationVO basicInformationVO : basicInformations) {
            BasicInformation basicInformation = selectBasicInformationById(basicInformationVO.getDealerId());
            basicInformation.setPriorityId(basicInformation.getId());
            basicInformation.setPriority(basicInformationVO.getPriority());
            updateBasicInformation(basicInformation);
        }

        //根据优先级，主机厂，授信类型查合同表里对应得合同，返回他的合同名称和合同地址

//        BasicInformation basicInformation = new BasicInformation();
//        basicInformation.setId(dealerid);
//        List<BasicInformation> dealerInformations = basicInformationMapper.selectDealerInformationList(dealerInformation);
//        BasicInformation basicInformation = selectBasicInformationById(basicInformations);
//        BasicInformation dealerInformation1 = dealerInformations.get(0);
//        basicInformation.setPriorityId(basicInformation.getId());
//        basicInformation.setPriority(priority);

        return 1;
    }

    //根据合同规则判断属于什么优先级然后再根据单条信息字段查匹配的合同
    @Override
    public Map<String, Object> matchTheContract(Map<String, Object> resultMap) {
        String dealerId = (String) resultMap.get("dealerId");
        String instanceId = (String) resultMap.get("instanceId");
        ApprovedLimitAndCondition approvedLimitAndCondition = new ApprovedLimitAndCondition();
        approvedLimitAndCondition.setDealerid(dealerId);
        approvedLimitAndCondition.setInstanceid(instanceId);
        List<ApprovedLimitAndCondition> approvedLimitAndConditions = approvedLimitAndConditionMapper.selectApprovedLimitAndConditionList(approvedLimitAndCondition);
        Map<String, Object> mapmtc = new HashMap<>();
        for (ApprovedLimitAndCondition alac : approvedLimitAndConditions) {
            if ((alac.getApprovedlimit() == null && alac.getApprovedcashdeposit() == null) && (alac.getProposallimit() != null && alac.getProposalcashdeposit() != null)) {
                Map<String, Object> map = new HashMap<>();
                map.put("priority", "4");
                map.put("sector", alac.getSector());
                map.put("limitType", alac.getLimittype());
                List<BasicContract> basicContracts = basicContractService.listBasicContract(map);
                mapmtc.put("BasicContract", basicContracts);
            }
        }
        return mapmtc;
    }

    //直接从生成的合同记录表里拿数据并拼接
    @Override
    @Transactional
    public List contracts(Map<String, Object> resultMap){
        String instanceId = (String) resultMap.get("instanceId");
        String subProcessId = (String)resultMap.get("subProcessId");
        if(StringUtils.isNotEmpty(subProcessId)){
            instanceId = subProcessId.split("-")[0];
        }
        if(StringUtils.isEmpty(instanceId)){
            throw new BaseException("instanceId不能为空");
        }
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        DealercodeContract dealercodeContract = new DealercodeContract();
        dealercodeContract.setInstanceId(instanceId);
        List<DealercodeContract> dealercodeContracts = dealercodeContractMapper.dealercodeContractListgroupby(dealercodeContract);

        for(DealercodeContract applac : dealercodeContracts) {
            Map<String, Object> objectObjectHashMap2 = new HashMap<>();
            for (int i = 0; i < list.size(); i++) {
                if(list.get(i).get("id").equals(applac.getDealerNameCN())){
                    objectObjectHashMap2 = list.get(i);
                }
            }
//            Map<String, Object> map = new HashMap<>();
            ArrayList<Map<String, Object>> list1 = new ArrayList<>();
            Map<String, Object> objectObjectHashMap3 = new HashMap<>();
//            map.put("Dealername", applac.getDealername());
//            map.put("sector", applac.getSector());
//            map.put("instanceId", instanceId);
//            List<BasicContract> basicContracts = this.matchTheContractNew(map);

//            DealercodeContract dealercodeContract1 = new DealercodeContract();
//            dealercodeContract1.setDealerNameCN(applac.getDealerNameCN());
//            dealercodeContract1.setSector(applac.getSector());
//            dealercodeContract1.setInstanceId(instanceId);
//            List<DealercodeContract> dealercodeContracts1 = dealercodeContractService.selectDealercodeContractList(dealercodeContract1);
            //改为从合同归档表拿数据，只显示归档合同的数据
            DealercodeContractFiling dealercodeContractFiling = new DealercodeContractFiling();
            dealercodeContractFiling.setDealerNameCN(applac.getDealerNameCN());
            dealercodeContractFiling.setSector(applac.getSector());
            dealercodeContractFiling.setInstanceId(instanceId);
            dealercodeContractFiling.setSubProcessId(subProcessId);
            List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingList(dealercodeContractFiling);
            objectObjectHashMap2.put("checkBackAll", 0);
          if(CollectionUtil.isNotEmpty(dealercodeContractFilings)){
                List<DealercodeContractFiling> dealercodeContractFilings1 = dealercodeContractFilingMapper.selectDealercodeContractFilingList3(dealercodeContractFilings.get(0));
                if(dealercodeContractFilings1!=null && dealercodeContractFilings1.size()>0){
                    objectObjectHashMap2.put("checkBackAll", 1);
                    StringBuilder stringBuilder1 = new StringBuilder();
                    for (DealercodeContractFiling contractFiling : dealercodeContractFilings1) {
                        stringBuilder1.append(contractFiling.getSubProcessId()+",");
                    }
                    stringBuilder1.deleteCharAt(stringBuilder1.length() - 1);
                    objectObjectHashMap2.put("checkBackAllMsg", "目前有待审批结束的流程编号:"+stringBuilder1);
                }
            }

            if(CollectionUtil.isNotEmpty(dealercodeContractFilings)){
                objectObjectHashMap2.put("id", applac.getDealerNameCN());
                objectObjectHashMap2.put("dealername", applac.getDealerNameCN());
                objectObjectHashMap3.put("contractName",applac.getSector());
                objectObjectHashMap3.put("children",dealercodeContractFilings);
                list1.add(objectObjectHashMap3);
            }

            if(null!=objectObjectHashMap2.get("children")){
                List<Map<String, Object>> children = (List<Map<String, Object>>) objectObjectHashMap2.get("children");
                children.addAll(list1);
            }else {
                if(CollectionUtil.isNotEmpty(list1)){
                    objectObjectHashMap2.put("children", list1);
                    list.add(objectObjectHashMap2);
                }
            }
        }
        System.out.println("生成合同中");
        return  list;
    }

    @Override
    public List contract(Map<String, Object> resultMap){
        String instanceId = (String) resultMap.get("instanceId");
        if(StringUtils.isEmpty(instanceId)){
            throw new BaseException("instanceId不能为空");
        }
        Map<String, Map<String, Object>> objectObjectHashMap = new HashMap<>();

        ArrayList<Map<String,Object>> list = new ArrayList<>();
        ProposalByCommericalAndMarketing approvedLimitAndCondition = new ProposalByCommericalAndMarketing();
        approvedLimitAndCondition.setInstanceId(instanceId);
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditions = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingListgroupby(approvedLimitAndCondition);
//        List<ProposalByCommericalAndMarketing> approvedLimitAndConditionsTwo = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingListgroupbyTwo(approvedLimitAndCondition);
//        ProposalByCommericalAndMarketing proposal = new ProposalByCommericalAndMarketing();
//        List<ProposalByCommericalAndMarketing> proposal1 = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(proposal);
//        for(ProposalByCommericalAndMarketing applacnew : approvedLimitAndConditionsTwo){
//            Map<String, Object> objectObjectHashMap2 = new HashMap<>();
//            objectObjectHashMap2.put("id", applacnew.getDealername());
//            objectObjectHashMap2.put("dealername", applacnew.getDealername());
//            objectObjectHashMap2.put("contractname", applacnew.getSector());
        for(ProposalByCommericalAndMarketing applac : approvedLimitAndConditions) {
            Map<String, Object> objectObjectHashMap2 = new HashMap<>();
            for (int i = 0; i < list.size(); i++) {
                if(list.get(i).get("id").equals(applac.getDealername())){
                    objectObjectHashMap2 = list.get(i);
                }
            }
            Map<String, Object> map = new HashMap<>();
//            Map<String, Object> objectObjectHashMap1 = new HashMap<>();
            ArrayList<Map<String, Object>> list1 = new ArrayList<>();
            Map<String, Object> objectObjectHashMap3 = new HashMap<>();
            map.put("Dealername", applac.getDealername());
            map.put("sector", applac.getSector());
            map.put("instanceId", instanceId);
            List<BasicContract> basicContracts = this.matchTheContractNew(map);

            objectObjectHashMap2.put("id", applac.getDealername());
            objectObjectHashMap2.put("dealername", applac.getDealername());
            objectObjectHashMap3.put("contractname",applac.getSector());
            objectObjectHashMap3.put("children",basicContracts);
            list1.add(objectObjectHashMap3);

            if(null!=objectObjectHashMap2.get("children")){
                List<Map<String, Object>> children = (List<Map<String, Object>>) objectObjectHashMap2.get("children");
                children.addAll(list1);
            }else {
                objectObjectHashMap2.put("children", list1);
                list.add(objectObjectHashMap2);

            }
            //判断是否存在key
//            if (objectObjectHashMap2.containsKey(applac.getDealername())) {
//                //存在就是取当前key的值，再把新值存进去
//                objectObjectHashMap.get(applac.getDealername()).putAll(objectObjectHashMap1);
//
//            } else {
//                //不存在就直接put
//                objectObjectHashMap.put(applac.getDealername(), objectObjectHashMap1);
//
//            }
        }



//        return list;
//        list.add(objectObjectHashMap);
        System.out.println("生成合同中");
        return  list;
    }

    //确定经销商,确定品牌进行匹配对应合同信息功能
    @Override
    @Transactional
    public List<BasicContract> matchTheContractNew(Map<String, Object> resultMap) {
        ArrayList<BasicContract> al = new ArrayList<>();
        String Dealername = (String) resultMap.get("Dealername");
        if(StringUtils.isEmpty(Dealername)){
            throw new BaseException("Dealername不能为空");
        }
        String sector = (String) resultMap.get("sector");
        if(StringUtils.isEmpty(sector)){
            throw new BaseException("sector不能为空");
        }
        String instanceId = (String) resultMap.get("instanceId");
        if(StringUtils.isEmpty(instanceId)){
            throw new BaseException("instanceId不能为空");
        }
        String limitType = (String) resultMap.get("limitType");
        if(StringUtils.isEmpty(instanceId)){
            throw new BaseException("limitType不能为空");
        }
        //根据流程id和经销商和品牌查Approved Limit and Condition的数据
        ProposalByCommericalAndMarketing approvedLimitAndCondition = new ProposalByCommericalAndMarketing();
        approvedLimitAndCondition.setInstanceId(instanceId);
        approvedLimitAndCondition.setDealername(Dealername);
        approvedLimitAndCondition.setSector(sector);

        //先判断表Approved Limit and Condition里的limttype为Normal的时候Proposal  limit>0条件成立，走第一个流程

        approvedLimitAndCondition.setLimitType("Normal");
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditions = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndCondition);
        approvedLimitAndCondition.setLimitType("Part");
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditionsFive = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndCondition);
        approvedLimitAndCondition.setLimitType("Demo");
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditionsOne = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndCondition);
        approvedLimitAndCondition.setLimitType("Temp");
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditionsTwo = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndCondition);
        approvedLimitAndCondition.setLimitType("Mrg");
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditionsThree = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndCondition);
        approvedLimitAndCondition.setLimitType("CB");
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditionsFour = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndCondition);
        //CB根据流程不同出的合同也不一样，所以这里查一下当前对应得流程
        AnnualReviewy annualReviewy = SpringUtils.getBean(AnnualReviewyMapper.class).selectAnnualReviewyByInstanceId(instanceId);
        //默认经销商和品牌都确定的情况下limittype不会重复
        ProposalByCommericalAndMarketing alac = new ProposalByCommericalAndMarketing();
        ProposalByCommericalAndMarketing alacOne = new ProposalByCommericalAndMarketing();
        ProposalByCommericalAndMarketing alacTwo = new ProposalByCommericalAndMarketing();
        ProposalByCommericalAndMarketing alacThree = new ProposalByCommericalAndMarketing();
        ProposalByCommericalAndMarketing alacFour = new ProposalByCommericalAndMarketing();
        ProposalByCommericalAndMarketing alacFive = new ProposalByCommericalAndMarketing();
        Date DateTime = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(new Date());
            DateTime = sdf.parse(format);
        }catch (Exception e){
            e.printStackTrace();
        }


        if (StringUtils.isNotEmpty(approvedLimitAndConditions)) {
            alac = approvedLimitAndConditions.get(0);
            CreditCondition cc = new CreditCondition();
            cc.setDealername(approvedLimitAndConditions.get(0).getDealername());
            cc.setSector(approvedLimitAndConditions.get(0).getSector());
            cc.setLimittype(approvedLimitAndConditions.get(0).getLimitType());
            cc.setInstanceid(instanceId);
            CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
            alac.setExpiryDateNew(creditCondition.getExpireddate());
        }
        if (StringUtils.isNotEmpty(approvedLimitAndConditionsFive)) {
            alacFive = approvedLimitAndConditionsFive.get(0);
            CreditCondition cc = new CreditCondition();
            cc.setDealername(approvedLimitAndConditionsFive.get(0).getDealername());
            cc.setSector(approvedLimitAndConditionsFive.get(0).getSector());
            cc.setLimittype(approvedLimitAndConditionsFive.get(0).getLimitType());
            cc.setInstanceid(instanceId);
            CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
            alacFive.setExpiryDateNew(creditCondition.getExpireddate());
        }
        if (StringUtils.isNotEmpty(approvedLimitAndConditionsOne)) {
            alacOne = approvedLimitAndConditionsOne.get(0);
            CreditCondition cc = new CreditCondition();
            cc.setDealername(approvedLimitAndConditionsOne.get(0).getDealername());
            cc.setSector(approvedLimitAndConditionsOne.get(0).getSector());
            cc.setLimittype(approvedLimitAndConditionsOne.get(0).getLimitType());
            cc.setInstanceid(instanceId);
            CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
            alacOne.setExpiryDateNew(creditCondition.getExpireddate());
        }
        if (StringUtils.isNotEmpty(approvedLimitAndConditionsTwo)) {
            alacTwo = approvedLimitAndConditionsTwo.get(0);
            CreditCondition cc = new CreditCondition();
            cc.setDealername(approvedLimitAndConditionsTwo.get(0).getDealername());
            cc.setSector(approvedLimitAndConditionsTwo.get(0).getSector());
            cc.setLimittype(approvedLimitAndConditionsTwo.get(0).getLimitType());
            cc.setInstanceid(instanceId);
            CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
            alacTwo.setExpiryDateNew(creditCondition.getExpireddate());
        }
        if (StringUtils.isNotEmpty(approvedLimitAndConditionsThree)) {
            alacThree = approvedLimitAndConditionsThree.get(0);
            CreditCondition cc = new CreditCondition();
            cc.setDealername(approvedLimitAndConditionsThree.get(0).getDealername());
            cc.setSector(approvedLimitAndConditionsThree.get(0).getSector());
            cc.setLimittype(approvedLimitAndConditionsThree.get(0).getLimitType());
            cc.setInstanceid(instanceId);
            CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
            alacThree.setExpiryDateNew(creditCondition.getExpireddate());
        }
        if (StringUtils.isNotEmpty(approvedLimitAndConditionsFour)) {
            alacFour = approvedLimitAndConditionsFour.get(0);
            CreditCondition cc = new CreditCondition();
            cc.setDealername(approvedLimitAndConditionsFour.get(0).getDealername());
            cc.setSector(approvedLimitAndConditionsFour.get(0).getSector());
            cc.setLimittype(approvedLimitAndConditionsFour.get(0).getLimitType());
            cc.setInstanceid(instanceId);
            CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
            alacFour.setExpiryDateNew(creditCondition.getExpireddate());
        }

        boolean isAR = false ;
        if(annualReviewy!=null && annualReviewy.getTitle()!=null && annualReviewy.getType().equals("annualVerification")){
            isAR = true;
        }
        boolean changNameFlag =false ;
        //查询是不是经销商更名
        DealerInformation dealerInformations = dealerInformationMapper.selectInfoBySectorAndDealerName(sector,Dealername);
        if(StringUtils.isNotEmpty(dealerInformations.getFormerDealerName()) && !dealerInformations.getFormerDealerName().equals(Dealername)){
            changNameFlag = true;
            DealerInformation dealerInformation = new DealerInformation();
            dealerInformation.setId(dealerInformations.getId());
            dealerInformation.setFormerDealerName(null);
            System.out.println("合同场景经销商更名");
            dealerInformationMapper.updateDealerInformation(dealerInformation);
        }
        //查询是不是终止的经销商
        //查询之前是不是termination
        DealerSectorLimitflag dealerSectorLimitflagTemp = new DealerSectorLimitflag();
        dealerSectorLimitflagTemp.setDealername(Dealername);
        dealerSectorLimitflagTemp.setSector(sector);
        boolean  isTermination = false;
        List<DealerSectorLimitflag> limitflags = dealerSectorLimitflagService.selectDealerSectorLimitflagList(dealerSectorLimitflagTemp);
        for (DealerSectorLimitflag sectorLimitflag : limitflags) {
            if(sectorLimitflag.getIsTermination()!=null && sectorLimitflag.getIsTermination() ==1){
                isTermination = true;
                break;
            }
        }

        DealerSectorLimitflag dealerSectorLimitflag = new DealerSectorLimitflag();
        dealerSectorLimitflag.setDealername(Dealername);
        dealerSectorLimitflag.setSector(sector);
        if(StringUtils.isEmpty(dealerSectorLimitflagService.selectDealerSectorLimitflagList(dealerSectorLimitflag))){
//            throw new BaseException("DealerSectorLimitflag表没对应得数据");
            DealerSectorLimitflag dealerSectorLimitflags = new DealerSectorLimitflag();
            dealerSectorLimitflags.setId(IdUtils.simpleUUID());
            dealerSectorLimitflags.setDealername(Dealername);
            dealerSectorLimitflags.setSector(sector);
            dealerSectorLimitflags.setNormalflag("true");
            dealerSectorLimitflags.setPartsFlag("true");
            dealerSectorLimitflags.setDemolflag("true");
            dealerSectorLimitflags.setTempflag("true");
            dealerSectorLimitflags.setMrgflag("true");
            dealerSectorLimitflags.setCbflag("true");
            dealerSectorLimitflags.setThreepartyflag("true");
            dealerSectorLimitflagMapper.insertDealerSectorLimitflag(dealerSectorLimitflags);
            annualReviewyService.saveDbLog("1","新增合同标识信息",null,instanceId,null,dealerSectorLimitflags,"CRO确认");

        }
        DealerSectorLimitflag dealerSectorLimitflagTwo = dealerSectorLimitflagService.selectDealerSectorLimitflagList(dealerSectorLimitflag).get(0);

        if (StringUtils.isNotNull(alac.getProposalLimit()) && alac.getProposalLimit() > 0 && alac.getExpiryDateNew().getTime()>DateTime.getTime()) {
            boolean isParts = false;
            if (StringUtils.isNotEmpty(approvedLimitAndConditionsFive) && StringUtils.isNotNull(alacFive.getProposalLimit()) && alacFive.getProposalLimit() > 0 && alacFive.getExpiryDateNew().getTime() > DateTime.getTime()) {
                //说明有Parts
                DealerSectorContractgroup dealerSectorContractgroup = new DealerSectorContractgroup();
                dealerSectorContractgroup.setDealername(Dealername);
                dealerSectorContractgroup.setSector(sector);
                dealerSectorContractgroup.setContractname("人民币循环贷款合同");
                List<DealerSectorContractgroup> dealerSectorContractgroups = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                if (StringUtils.isNotEmpty(dealerSectorContractgroups) && dealerSectorLimitflagTwo.getPartsFlag().equals("true")) {
                    isParts = true;
                }

            }
            if (isParts && sector.toUpperCase().equals("PEUGEOT")) {
                //出场景10
                BasicContract basicContract = new BasicContract();
                basicContract.setPriority("10");
                basicContract.setLimittype("Normal");
                basicContract.setSector(sector);
                al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同New application
                //对应得flag变成false
                DealerSectorLimitflag flag = new DealerSectorLimitflag();
                flag.setDealername(Dealername);
                flag.setSector(sector);
                DealerSectorLimitflag oldBean = new DealerSectorLimitflag();
                List<DealerSectorLimitflag> dealerSectorLimitflags = dealerSectorLimitflagService.selectDealerSectorLimitflagList(flag);
                if (StringUtils.isNotEmpty(dealerSectorLimitflags)) {
                    oldBean = dealerSectorLimitflags.get(0);
                }
                flag.setPartsFlag("false");
                dealerSectorLimitflagService.updateDealerSectorLimitflag(flag);
                annualReviewyService.saveDbLog("3", "修改合同标识信息", null, instanceId, oldBean, flag, "CRO确认");
            }else {
                if (dealerSectorLimitflagTwo.getNormalflag().equals("true") && (isAR || changNameFlag || isTermination)) {
                    BasicContract basicContract = new BasicContract();
                    basicContract.setPriority("4");
                    basicContract.setLimittype(alac.getLimitType());
                    basicContract.setSector(sector);
                    al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同New application

                    //这里也需要判断包含parts

                    //对应得flag变成false
                    DealerSectorLimitflag flag = new DealerSectorLimitflag();
                    flag.setDealername(Dealername);
                    flag.setSector(sector);
                    DealerSectorLimitflag oldBean = new DealerSectorLimitflag();
                    List<DealerSectorLimitflag> dealerSectorLimitflags = dealerSectorLimitflagService.selectDealerSectorLimitflagList(flag);
                    if (StringUtils.isNotEmpty(dealerSectorLimitflags)) {
                        oldBean = dealerSectorLimitflags.get(0);
                    }
                    if (StringUtils.isNotEmpty(approvedLimitAndConditionsFive) && StringUtils.isNotNull(alacFive.getProposalLimit()) && alacFive.getProposalLimit() > 0 && alacFive.getExpiryDateNew().getTime() > DateTime.getTime()) {
                        flag.setPartsFlag("false");
                    }
                    flag.setNormalflag("false");
                    flag.setThreepartyflag("false");
                    dealerSectorLimitflagService.updateDealerSectorLimitflag(flag);
                    annualReviewyService.saveDbLog("3", "修改合同标识信息", null, instanceId, oldBean, flag, "CRO确认");

                } else {
                    //否则就判断h_dealer_sector_contractgroup表里的合同组里有没有《人民币循环贷款主合同号》
                    DealerSectorContractgroup dealerSectorContractgroup = new DealerSectorContractgroup();
                    dealerSectorContractgroup.setDealername(Dealername);
                    dealerSectorContractgroup.setSector(sector);
                    dealerSectorContractgroup.setContractname("人民币循环贷款合同");//不知道合同号，先用合同名称测试
    //                if(StringUtils.isEmpty(dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup))){
    //                    throw new BaseException("DealerSectorContractgroup表没对应得数据");
    //                }
                    List<DealerSectorContractgroup> dealerSectorContractgroups = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);

    //                DealerSectorContractgroup dealerSectorContractgroup1 = new DealerSectorContractgroup();
    //                dealerSectorContractgroup1.setDealername(Dealername);
    //                dealerSectorContractgroup1.setSector(sector);
    //                dealerSectorContractgroup1.setContractname("人民币循环贷款合同附件三");//人民币循环贷款主合同跟合同三附件合同号一样，有附件三必有主合同号
    //                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup1);

                    if (StringUtils.isEmpty(dealerSectorContractgroups)) { //为空就再走New  application业务场景
                        BasicContract basicContract = new BasicContract();
                        basicContract.setPriority("4");
                        basicContract.setLimittype(alac.getLimitType());
                        basicContract.setSector(sector);
                        al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同New application
                        //对应得flag变成false
                        DealerSectorLimitflag flag = new DealerSectorLimitflag();
                        flag.setDealername(Dealername);
                        flag.setSector(sector);
                        DealerSectorLimitflag oldBean = new DealerSectorLimitflag();
                        List<DealerSectorLimitflag> dealerSectorLimitflags = dealerSectorLimitflagService.selectDealerSectorLimitflagList(flag);
                        if (StringUtils.isNotEmpty(dealerSectorLimitflags)) {
                            oldBean = dealerSectorLimitflags.get(0);
                        }
                        if (StringUtils.isNotEmpty(approvedLimitAndConditionsFive) && StringUtils.isNotNull(alacFive.getProposalLimit()) && alacFive.getProposalLimit() > 0 && alacFive.getExpiryDateNew().getTime() > DateTime.getTime()) {
                            flag.setPartsFlag("false");
                        }
                        flag.setNormalflag("false");
                        flag.setThreepartyflag("false");
                        dealerSectorLimitflagService.updateDealerSectorLimitflag(flag);
                        annualReviewyService.saveDbLog("3", "修改合同标识信息", null, instanceId, oldBean, flag, "CRO确认");

                    } else {
                  /*      if (dealerSectorLimitflagTwo.getThreepartyflag().equals("true")) {
                            BasicContract basicContract = new BasicContract();
                            basicContract.setPriority("6");
                            basicContract.setLimittype(alac.getLimitType());
                            basicContract.setSector(sector);
                            al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Three Party Info Change
                            //对应得flag变成false
                            DealerSectorLimitflag flag = new DealerSectorLimitflag();
                            flag.setDealername(Dealername);
                            flag.setSector(sector);
                            DealerSectorLimitflag oldBean = new DealerSectorLimitflag();
                            List<DealerSectorLimitflag> dealerSectorLimitflags = dealerSectorLimitflagService.selectDealerSectorLimitflagList(flag);
                            if(StringUtils.isNotEmpty(dealerSectorLimitflags)){
                                oldBean =  dealerSectorLimitflags.get(0);
                            }
                            flag.setThreepartyflag("false");
                            dealerSectorLimitflagService.updateDealerSectorLimitflag(flag);
                            annualReviewyService.saveDbLog("3","修改合同标识信息",null,instanceId,oldBean,flag,"CRO确认");

                        }*/
                        //此处并行，条件成立可同时出两个业务场景的合同
                        boolean sense = false;
                        //取对应流程的表的全部数据，判断currentname跟proposalname是否一致，只要两个值不一样就出这个合同Change guarantee conditions
                        Securities guaranteeInformation = new Securities();
                        guaranteeInformation.setInstanceId(instanceId);
                        guaranteeInformation.setDealername(Dealername);
                        List<Securities> guaranteeInformations = securitiesMapper.selectSecuritiesListTypeIsnotnull(guaranteeInformation);
                        if (StringUtils.isNotEmpty(guaranteeInformations)) {
                            for (Securities gif : guaranteeInformations) {
                                if (StringUtils.isEmpty(gif.getCurrentNameCN())) {
                                    gif.setCurrentNameCN("");
                                }
                                if (StringUtils.isEmpty(gif.getProposalNameCN())) {
                                    gif.setProposalNameCN("");
                                }
                                String currentNameCN = gif.getCurrentNameCN();
                                String proposalNameCN = gif.getProposalNameCN();
                                String currentNameCNStr = currentNameCN.replace("（", "(").replace("）", ")").replace(" ", "").toLowerCase();
                                String proposalNameCNStr = proposalNameCN.replace("（", "(").replace("）", ")").replace(" ", "").toLowerCase();

                                if ((!currentNameCNStr.equals(proposalNameCNStr))) {

                                    sense = true;

                                }
                            }
                        }
                        if (sense) {
                            BasicContract basicContract = new BasicContract();
                            basicContract.setPriority("3");
                            basicContract.setLimittype(alac.getLimitType());
                            basicContract.setSector(sector);
                            al.addAll(basicContractService.selectBasicContractList(basicContract));//只要两个值不一样就出这个合同Change guarantee conditions
                        } else {
                            if (StringUtils.isEmpty(alacFour.getDealername())) {
                                alacFour.setApprovedLimit((long) 0);
                                alacFour.setProposalLimit((long) 0);
                            }
                            if (StringUtils.isNull(alac.getApprovedLimit())) {
                                alac.setApprovedLimit(new Long(0));
                            }
                            if (StringUtils.isNull(alacFour.getApprovedLimit())) {
                                alacFour.setApprovedLimit(new Long(0));
                            }
                            if (StringUtils.isEmpty(alac.getApprovedCashDeposit())) {
                                alac.setApprovedCashDeposit("0");
                            }

                            //判断表h_approved_limit_and_condition上的（current里的normallimit+cblimit != proposal里的normallimit+cblimit）或者 （normal上current里的Deposit% ！= proposal里的Deposit%）
                            if ((alac.getApprovedLimit() + alacFour.getApprovedLimit() != alac.getProposalLimit() + alacFour.getProposalLimit()) || (!alac.getApprovedCashDeposit().equals(alac.getProposalCashDeposit()))
                                 || (StringUtils.isNotEmpty(approvedLimitAndConditionsFive) && alacFive.getApprovedLimit()+0 != alacFive.getProposalLimit()+0)
                                || (StringUtils.isNotEmpty(approvedLimitAndConditionsFive) && !alacFive.getApprovedCashDeposit().equals(alacFive.getProposalCashDeposit()) )) {
                                BasicContract basicContract = new BasicContract();
                                basicContract.setPriority("2");
                                basicContract.setLimittype(alac.getLimitType());
                                basicContract.setSector(sector);
                                al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Limit amount/ratio change
                            } else {
                                CreditCondition cc = new CreditCondition();
                                cc.setDealername(Dealername);
                                cc.setSector(sector);
                                cc.setLimittype(alac.getLimitType());
                                cc.setInstanceid(instanceId);
                                if (StringUtils.isEmpty(creditConditionService.selectCreditConditionList(cc))) {
                                    throw new BaseException("CreditCondition表没对应得数据");
                                }
                                CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
                                WholesalePerformanceCurrently wpc = new WholesalePerformanceCurrently();
                                wpc.setDealername(Dealername);
                                wpc.setSector(sector);
                                wpc.setLimitType(alac.getLimitType());
                                wpc.setInstanceId(instanceId);
    //                                if(StringUtils.isEmpty(wholesalePerformanceCurrentlyService.selectWholesalePerformanceCurrentlyList(wpc))){
    //                                    throw new BaseException("WholesalePerformanceCurrently表没对应得数据");
    //                                }
                                List<WholesalePerformanceCurrently> wholesalePerformanceCurrently = wholesalePerformanceCurrentlyService.selectWholesalePerformanceCurrentlyList(wpc);
                                String a = "";
                                if (StringUtils.isNotEmpty(wholesalePerformanceCurrently)) {
                                    a = wholesalePerformanceCurrently.get(0).getExpiryDate();
                                }
                                //判断CreditCondition表的日期不等于WholesalePerformanceCurrently表的日期，就走这个合同
                                String dateToStr = "";
                                if (StringUtils.isNotNull(creditCondition.getExpireddate())) {
                                    dateToStr = DateUtils.parseDateToStr("yyyy/MM/dd", creditCondition.getExpireddate());
                                } else {
                                    dateToStr = "";
                                }

                                if (!dateToStr.equals(a)) {
                                    BasicContract basicContract = new BasicContract();
                                    basicContract.setPriority("1");
                                    basicContract.setLimittype(alac.getLimitType());
                                    basicContract.setSector(sector);
                                    al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Expiry Date extension
                                }else{
                                    CreditCondition ccc = new CreditCondition();
                                    ccc.setDealername(Dealername);
                                    ccc.setSector(sector);
                                    ccc.setLimittype("Part");
                                    ccc.setInstanceid(instanceId);
                                    if (StringUtils.isNotEmpty(creditConditionService.selectCreditConditionList(ccc))) {
                                        CreditCondition creditConditionPart = creditConditionService.selectCreditConditionList(ccc).get(0);
                                        WholesalePerformanceCurrently wpcPart = new WholesalePerformanceCurrently();
                                        wpcPart.setDealername(Dealername);
                                        wpcPart.setSector(sector);
                                        wpcPart.setLimitType("Part");
                                        wpcPart.setInstanceId(instanceId);
                                        List<WholesalePerformanceCurrently> wholesalePerformanceCurrentlyPart = wholesalePerformanceCurrentlyService.selectWholesalePerformanceCurrentlyList(wpcPart);
                                        String b = "";
                                        if (StringUtils.isNotEmpty(wholesalePerformanceCurrentlyPart)) {
                                            b = wholesalePerformanceCurrently.get(0).getExpiryDate();
                                        }
                                        String dateToStrPart = "";
                                        if (StringUtils.isNotNull(creditConditionPart.getExpireddate())) {
                                            dateToStrPart = DateUtils.parseDateToStr("yyyy/MM/dd", creditConditionPart.getExpireddate());
                                        } else {
                                            dateToStrPart = "";
                                        }
                                        if (!dateToStrPart.equals(b)) {
                                            BasicContract basicContract = new BasicContract();
                                            basicContract.setPriority("1");
                                            basicContract.setLimittype(alac.getLimitType());
                                            basicContract.setSector(sector);
                                            al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Expiry Date extension
                                        }
                                    }
                                }

                            }
                        }

                    }
                }
            }
        }
        if (StringUtils.isNotNull(alacOne.getProposalLimit()) && alacOne.getProposalLimit() > 0 && alacOne.getExpiryDateNew().getTime()>DateTime.getTime()) {  //判断表Approved Limit and Condition里的limttype为demo的时候Proposal  limit>0条件成立，走第二个流程
//            DealerSectorLimitflag dealerSectorLimitflag = new DealerSectorLimitflag();
//            dealerSectorLimitflag.setDealerid(dealerId);
//            dealerSectorLimitflag.setSector(sector);
//            DealerSectorLimitflag dealerSectorLimitflagTwo = dealerSectorLimitflagService.selectDealerSectorLimitflagList(dealerSectorLimitflag).get(0);
            //判断DemolFlag=true ,就走New application业务场景('优先级New application(4) >Three Party Info Change(6) > Change guarantee conditions(3) > Limit amount/ratio change(2) > Limit expiry date extension(1)；另外还有Temp Limit(7)、MRG limit(8)')
            if (dealerSectorLimitflagTwo.getDemolflag().equals("true") && (isAR || changNameFlag || isTermination)) {
                BasicContract basicContract = new BasicContract();
                basicContract.setPriority("4");
                basicContract.setLimittype(alacOne.getLimitType());
                basicContract.setSector(sector);
                al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同New application
                //对应得flag变成false
                DealerSectorLimitflag flag = new DealerSectorLimitflag();
                flag.setDealername(Dealername);
                flag.setSector(sector);
                DealerSectorLimitflag oldBean = new DealerSectorLimitflag();
                List<DealerSectorLimitflag> dealerSectorLimitflags = dealerSectorLimitflagService.selectDealerSectorLimitflagList(flag);
                if(StringUtils.isNotEmpty(dealerSectorLimitflags)){
                    oldBean =  dealerSectorLimitflags.get(0);
                }
                flag.setDemolflag("false");
                dealerSectorLimitflagService.updateDealerSectorLimitflag(flag);
                annualReviewyService.saveDbLog("3","修改合同标识信息",null,instanceId,oldBean,flag,"CRO确认");

            } else {
                //否则就判断h_dealer_sector_contractgroup表里的合同组里有没有《试驾车循环贷款合同号》
                DealerSectorContractgroup dealerSectorContractgroup = new DealerSectorContractgroup();
                dealerSectorContractgroup.setDealername(Dealername);
                dealerSectorContractgroup.setSector(sector);
                dealerSectorContractgroup.setContractname("试乘试驾车贷款合同");//不知道合同号，先用合同名称测
                List<DealerSectorContractgroup> dealerSectorContractgroups = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                if (StringUtils.isEmpty(dealerSectorContractgroups)) { //为空就再走New  application业务场景
                    BasicContract basicContract = new BasicContract();
                    basicContract.setPriority("4");
                    basicContract.setLimittype(alacOne.getLimitType());
                    basicContract.setSector(sector);
                    al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同New application

                    //对应得flag变成false
                    DealerSectorLimitflag flag = new DealerSectorLimitflag();
                    flag.setDealername(Dealername);
                    flag.setSector(sector);
                    DealerSectorLimitflag oldBean = new DealerSectorLimitflag();
                    List<DealerSectorLimitflag> dealerSectorLimitflags = dealerSectorLimitflagService.selectDealerSectorLimitflagList(flag);
                    if(StringUtils.isNotEmpty(dealerSectorLimitflags)){
                        oldBean =  dealerSectorLimitflags.get(0);
                    }
                    flag.setDemolflag("false");
                    dealerSectorLimitflagService.updateDealerSectorLimitflag(flag);
                    annualReviewyService.saveDbLog("3","修改合同标识信息",null,instanceId,oldBean,flag,"CRO确认");
                } else {
                    boolean sense = false;
                    //取对应流程的表的全部数据，判断currentname跟proposalname是否一致，只要两个值不一样就出这个合同Change guarantee conditions
                    Securities guaranteeInformation = new Securities();
                    guaranteeInformation.setInstanceId(instanceId);
                    guaranteeInformation.setDealername(Dealername);
                    List<Securities> guaranteeInformations = securitiesMapper.selectSecuritiesListTypeIsnotnull(guaranteeInformation);
                    if(StringUtils.isNotEmpty(guaranteeInformations)) {
                        for (Securities gif : guaranteeInformations) {
                            if (StringUtils.isEmpty(gif.getCurrentNameCN())) {
                                gif.setCurrentNameCN("");
                            }
                            if (StringUtils.isEmpty(gif.getProposalNameCN())) {
                                gif.setProposalNameCN("");
                            }
                            String currentNameCN = gif.getCurrentNameCN();
                            String proposalNameCN = gif.getProposalNameCN();
                            String currentNameCNStr = currentNameCN.replace("（", "(").replace("）", ")").replace(" ", "").toLowerCase();
                            String proposalNameCNStr = proposalNameCN.replace("（", "(").replace("）", ")").replace(" ", "").toLowerCase();

                            if ((!currentNameCNStr.equals(proposalNameCNStr))) {

                                sense = true;

                            }
                        }
                    }
                    if (sense) {
                        BasicContract basicContract = new BasicContract();
                        basicContract.setPriority("3");
                        basicContract.setLimittype(alacOne.getLimitType());
                        basicContract.setSector(sector);
                        al.addAll(basicContractService.selectBasicContractList(basicContract));//只要两个值不一样就出这个合同Change guarantee conditions
                    } else {
                        if(StringUtils.isNull(alacOne.getApprovedLimit())){
                            alacOne.setApprovedLimit(new Long(0));
                        }
                        if(StringUtils.isEmpty(alacOne.getApprovedCashDeposit())){
                            alacOne.setApprovedCashDeposit("0");
                        }
                        //判断表h_approved_limit_and_condition里的current跟proposal不一致的时候
                        if ((!alacOne.getApprovedLimit() .equals(alacOne.getProposalLimit())) || (!alacOne.getApprovedCashDeposit().equals(alacOne.getProposalCashDeposit()))) {
                            BasicContract basicContract = new BasicContract();
                            basicContract.setPriority("2");
                            basicContract.setLimittype(alacOne.getLimitType());
                            basicContract.setSector(sector);
                            al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Limit amount/ratio change
                        } else {
                            CreditCondition cc = new CreditCondition();
                            cc.setDealername(Dealername);
                            cc.setSector(sector);
                            cc.setLimittype(alacOne.getLimitType());
                            cc.setInstanceid(instanceId);
                            CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
                            WholesalePerformanceCurrently wpc = new WholesalePerformanceCurrently();
                            wpc.setDealername(Dealername);
                            wpc.setSector(sector);
                            wpc.setLimitType(alacOne.getLimitType());
                            wpc.setInstanceId(instanceId);
                            List<WholesalePerformanceCurrently> wholesalePerformanceCurrently = wholesalePerformanceCurrentlyService.selectWholesalePerformanceCurrentlyList(wpc);
                            String a = "";
                            if(StringUtils.isNotEmpty(wholesalePerformanceCurrently)){
                                a = wholesalePerformanceCurrently.get(0).getExpiryDate();
                            }
                            //判断CreditCondition表的日期不等于WholesalePerformanceCurrently表的日期，就走这个合同
                            String dateToStr = "";
                            if(StringUtils.isNotNull(creditCondition.getExpireddate())){
                                dateToStr = DateUtils.parseDateToStr("yyyy/MM/dd", creditCondition.getExpireddate());
                            }else {
                                dateToStr="";
                            }
                            if (!dateToStr.equals(a)) {
                                BasicContract basicContract = new BasicContract();
                                basicContract.setPriority("1");
                                basicContract.setLimittype(alacOne.getLimitType());
                                basicContract.setSector(sector);
                                al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Expiry Date extension
                            }
                        }
                    }

                }
            }

        }
        if (StringUtils.isNotNull(alacTwo.getProposalLimit()) && alacTwo.getProposalLimit() > 0 && alacTwo.getExpiryDateNew().getTime()>DateTime.getTime()) {  //判断表Approved Limit and Condition里的limttype为temp的时候Proposal  limit>0条件成立，走第三个流程
            //判断TempFlag=true ,就走Temp Limit业务场景('优先级New application(4) >Three Party Info Change(6) > Change guarantee conditions(3) > Limit amount/ratio change(2) > Limit expiry date extension(1)；另外还有Temp Limit(7)、MRG limit(8)')
            //查询是不是新的经销商
            if (dealerSectorLimitflagTwo.getTempflag().equals("true") && (isAR || changNameFlag || isTermination)) {
                BasicContract basicContract = new BasicContract();
                basicContract.setPriority("7");
                basicContract.setLimittype(alacTwo.getLimitType());
                basicContract.setSector(sector);
                al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Temp Limit
                //对应得flag变成false
                DealerSectorLimitflag flag = new DealerSectorLimitflag();
                flag.setDealername(Dealername);
                flag.setSector(sector);
                DealerSectorLimitflag oldBean = new DealerSectorLimitflag();
                List<DealerSectorLimitflag> dealerSectorLimitflags = dealerSectorLimitflagService.selectDealerSectorLimitflagList(flag);
                if(StringUtils.isNotEmpty(dealerSectorLimitflags)){
                    oldBean =  dealerSectorLimitflags.get(0);
                }
                flag.setTempflag("false");
                dealerSectorLimitflagService.updateDealerSectorLimitflag(flag);
                annualReviewyService.saveDbLog("3","修改合同标识信息",null,instanceId,oldBean,flag,"CRO确认");

            }else{
                DealerSectorContractgroup dealerSectorContractgroup = new DealerSectorContractgroup();
                dealerSectorContractgroup.setDealername(Dealername);
                dealerSectorContractgroup.setSector(sector);
                dealerSectorContractgroup.setContractname("人民币循环贷款合同附件三");//不知道合同号，先用合同名称测
                List<DealerSectorContractgroup> dealerSectorContractgroups = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                if (StringUtils.isEmpty(dealerSectorContractgroups)) { //为空就再走New  application业务场景
                    BasicContract basicContract = new BasicContract();
                    basicContract.setPriority("7");
                    basicContract.setLimittype(alacTwo.getLimitType());
                    basicContract.setSector(sector);
                    al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Temp Limit
                    //对应得flag变成false
                    DealerSectorLimitflag flag = new DealerSectorLimitflag();
                    flag.setDealername(Dealername);
                    flag.setSector(sector);
                    DealerSectorLimitflag oldBean = new DealerSectorLimitflag();
                    List<DealerSectorLimitflag> dealerSectorLimitflags = dealerSectorLimitflagService.selectDealerSectorLimitflagList(flag);
                    if(StringUtils.isNotEmpty(dealerSectorLimitflags)){
                        oldBean =  dealerSectorLimitflags.get(0);
                    }
                    flag.setTempflag("false");
                    dealerSectorLimitflagService.updateDealerSectorLimitflag(flag);
                    annualReviewyService.saveDbLog("3","修改合同标识信息",null,instanceId,oldBean,flag,"CRO确认");
                }else {
                    boolean sense = false;
                    //取对应流程的表的全部数据，判断currentname跟proposalname是否一致，只要两个值不一样或者--->
                    Securities guaranteeInformation = new Securities();
                    guaranteeInformation.setInstanceId(instanceId);
                    guaranteeInformation.setDealername(Dealername);
                    List<Securities> guaranteeInformations = securitiesMapper.selectSecuritiesListTypeIsnotnull(guaranteeInformation);
                    if(StringUtils.isNotEmpty(guaranteeInformations)) {
                        for (Securities gif : guaranteeInformations) {
                            if (StringUtils.isEmpty(gif.getCurrentNameCN())) {
                                gif.setCurrentNameCN("");
                            }
                            if (StringUtils.isEmpty(gif.getProposalNameCN())) {
                                gif.setProposalNameCN("");
                            }
                            String currentNameCN = gif.getCurrentNameCN();
                            String proposalNameCN = gif.getProposalNameCN();
                            String currentNameCNStr = currentNameCN.replace("（", "(").replace("）", ")").replace(" ", "").toLowerCase();
                            String proposalNameCNStr = proposalNameCN.replace("（", "(").replace("）", ")").replace(" ", "").toLowerCase();

                            if ((!currentNameCNStr.equals(proposalNameCNStr))) {

                                sense = true;

                            }
                        }
                    }
                    //表h_approved_limit_and_condition里的current跟proposal不一致的时候或者--->
                    CreditCondition cc = new CreditCondition();
                    cc.setDealername(Dealername);
                    cc.setSector(sector);
                    cc.setLimittype(alacTwo.getLimitType());
                    cc.setInstanceid(instanceId);
                    CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
                    WholesalePerformanceCurrently wpc = new WholesalePerformanceCurrently();
                    wpc.setDealername(Dealername);
                    wpc.setSector(sector);
                    wpc.setLimitType(alacTwo.getLimitType());
                    wpc.setInstanceId(instanceId);
                    List<WholesalePerformanceCurrently> wholesalePerformanceCurrently = wholesalePerformanceCurrentlyService.selectWholesalePerformanceCurrentlyList(wpc);
                    String a = "";
                    if(StringUtils.isNotEmpty(wholesalePerformanceCurrently)){
                        a = wholesalePerformanceCurrently.get(0).getExpiryDate();
                    }
                    //CreditCondition表的日期不等于WholesalePerformanceCurrently表的日期，就再出Temp Limit这个合同
                    String dateToStr = "";
                    if(StringUtils.isNotNull(creditCondition.getExpireddate())){
                        Date expireddate = creditCondition.getExpireddate();
                        dateToStr = DateUtils.parseDateToStr("yyyy/MM/dd", expireddate);
                    }
//                if (sense || (!alacTwo.getApprovedLimit().equals(alacTwo.getProposalLimit())) || creditCondition.getExpireddate().compareTo(wholesalePerformanceCurrently.getExpiryDate()) != 0) {
                    if(StringUtils.isNull(alacTwo.getApprovedLimit())){
                        alacTwo.setApprovedLimit(new Long(0));
                    }
                    if (sense || (!alacTwo.getApprovedLimit().equals(alacTwo.getProposalLimit())) || !dateToStr.equals(a)) {
                        BasicContract basicContract = new BasicContract();
                        basicContract.setPriority("7");
                        basicContract.setLimittype(alacTwo.getLimitType());
                        basicContract.setSector(sector);
                        al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Temp Limit
                    }
                }
            }
        }
        if (StringUtils.isNotNull(alacThree.getProposalLimit()) && alacThree.getProposalLimit() > 0 && alacThree.getExpiryDateNew().getTime()>DateTime.getTime()) {  //判断表Approved Limit and Condition里的limttype为mrg的时候Proposal  limit>0条件成立，走第四个流程
            //判断MRGFlag=true ,就走MRG limit业务场景('优先级New application(4) >Three Party Info Change(6) > Change guarantee conditions(3) > Limit amount/ratio change(2) > Limit expiry date extension(1)；另外还有Temp Limit(7)、MRG limit(8)')
            if (dealerSectorLimitflagTwo.getMrgflag().equals("true") && (isAR || changNameFlag || isTermination)) {
                BasicContract basicContract = new BasicContract();
                basicContract.setPriority("8");
                basicContract.setLimittype(alacThree.getLimitType());
                basicContract.setSector(sector);
                al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同MRG limit
                //对应得flag变成false
                DealerSectorLimitflag flag = new DealerSectorLimitflag();
                flag.setDealername(Dealername);
                flag.setSector(sector);
                DealerSectorLimitflag oldBean = new DealerSectorLimitflag();
                List<DealerSectorLimitflag> dealerSectorLimitflags = dealerSectorLimitflagService.selectDealerSectorLimitflagList(flag);
                if(StringUtils.isNotEmpty(dealerSectorLimitflags)){
                    oldBean =  dealerSectorLimitflags.get(0);
                }
                flag.setMrgflag("false");
                dealerSectorLimitflagService.updateDealerSectorLimitflag(flag);
                annualReviewyService.saveDbLog("3","修改合同标识信息",null,instanceId,oldBean,flag,"CRO确认");

            } else {
                //表h_approved_limit_and_condition里的current跟proposal不一致的时候或者--->
//                if ((!alacThree.getCurrentlimit().equals(alacThree.getAprovedlimit()))) {}
                CreditCondition cc = new CreditCondition();
                cc.setDealername(Dealername);
                cc.setSector(sector);
                cc.setLimittype(alacThree.getLimitType());
                cc.setInstanceid(instanceId);
                CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
                WholesalePerformanceCurrently wpc = new WholesalePerformanceCurrently();
                wpc.setDealername(Dealername);
                wpc.setSector(sector);
                wpc.setLimitType(alacThree.getLimitType());
                wpc.setInstanceId(instanceId);
                List<WholesalePerformanceCurrently> wholesalePerformanceCurrently = wholesalePerformanceCurrentlyService.selectWholesalePerformanceCurrentlyList(wpc);
                String a = "";
                if(StringUtils.isNotEmpty(wholesalePerformanceCurrently)){
                    a = wholesalePerformanceCurrently.get(0).getExpiryDate();
                }
                String dateToStr = "";
                if(StringUtils.isNotNull(creditCondition.getExpireddate())){
                    Date expireddate = creditCondition.getExpireddate();
                    dateToStr = DateUtils.parseDateToStr("yyyy/MM/dd", expireddate);
                }
                if(StringUtils.isNull(alacThree.getApprovedLimit())){
                    alacThree.setApprovedLimit(new Long(0));
                }
                //CreditCondition表的日期不等于WholesalePerformanceCurrently表的日期，就再出MRG limit这个合同
                if ((!alacThree.getApprovedLimit().equals(alacThree.getProposalLimit())) || !dateToStr.equals(a)) {
                    BasicContract basicContract = new BasicContract();
                    basicContract.setPriority("8");
                    basicContract.setLimittype(alacThree.getLimitType());
                    basicContract.setSector(sector);
                    al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同MRG limit
                }
            }
        }
        //当他是CB流程的时候出limtTyoe为CB one-off fleet这个的合同，不是就出另一个
        String cb = "";
        if (annualReviewy.getType().equals("creditBridge")) {
            cb = "CB one-off fleet";
        }else {
            cb = "CB Revolving";
        }
        if (StringUtils.isNotNull(alacFour.getProposalLimit()) && alacFour.getProposalLimit() > 0 && alacFour.getExpiryDateNew().getTime()>DateTime.getTime()) {  //判断表Approved Limit and Condition里的limttype为cb的时候Proposal  limit>0条件成立，走第五个个流程
            //判断CBFlag=true ,就走New application业务场景('优先级New application(4) >Three Party Info Change(6) > Change guarantee conditions(3) > Limit amount/ratio change(2) > Limit expiry date extension(1)；另外还有Temp Limit(7)、MRG limit(8)')
            if(cb.equals("CB Revolving")) {
                if (dealerSectorLimitflagTwo.getCbflag().equals("true") && (isAR || changNameFlag || isTermination)) {
                    BasicContract basicContract = new BasicContract();
                    basicContract.setPriority("4");
                    basicContract.setLimittype(cb);
                    basicContract.setSector(sector);
                    al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同New application
                    //对应得flag变成false
                    DealerSectorLimitflag flag = new DealerSectorLimitflag();
                    flag.setDealername(Dealername);
                    flag.setSector(sector);
                    DealerSectorLimitflag oldBean = new DealerSectorLimitflag();
                    List<DealerSectorLimitflag> dealerSectorLimitflags = dealerSectorLimitflagService.selectDealerSectorLimitflagList(flag);
                    if(StringUtils.isNotEmpty(dealerSectorLimitflags)){
                        oldBean =  dealerSectorLimitflags.get(0);
                    }
                    flag.setCbflag("false");
                    dealerSectorLimitflagService.updateDealerSectorLimitflag(flag);
                    annualReviewyService.saveDbLog("3","修改合同标识信息",null,instanceId,oldBean,flag,"CRO确认");

                } else {
                    //否则就判断h_dealer_sector_contractgroup表里的合同组里有没有《CB改装车协议(循环)》或者--->
                    DealerSectorContractgroup dealerSectorContractgroup = new DealerSectorContractgroup();
                    dealerSectorContractgroup.setDealername(Dealername);
                    dealerSectorContractgroup.setSector(sector);
                    dealerSectorContractgroup.setContractname("CB 改装车大客户延期补充协议");//不知道合同号，先用合同名称测
                    List<DealerSectorContractgroup> dealerSectorContractgroups = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                    //TODO 如果是CB流程的话，这里是否还是判断改装车，因为CB流程出的是大客户
//                if (StringUtils.isEmpty(dealerSectorContractgroups)) {
                    boolean sense = false;
                    //取对应流程的表的全部数据，判断currentname跟proposalname是否一致，只要两个值不一样
                    Securities guaranteeInformation = new Securities();
                    guaranteeInformation.setInstanceId(instanceId);
                    guaranteeInformation.setDealername(Dealername);
                    List<Securities> guaranteeInformations = securitiesMapper.selectSecuritiesListTypeIsnotnull(guaranteeInformation);
                    if (StringUtils.isNotEmpty(guaranteeInformations)) {
                        for (Securities gif : guaranteeInformations) {
                            if (StringUtils.isEmpty(gif.getCurrentNameCN())) {
                                gif.setCurrentNameCN("");
                            }
                            if (StringUtils.isEmpty(gif.getProposalNameCN())) {
                                gif.setProposalNameCN("");
                            }
                            String currentNameCN = gif.getCurrentNameCN();
                            String proposalNameCN = gif.getProposalNameCN();
                            String currentNameCNStr = currentNameCN.replace("（", "(").replace("）", ")").replace(" ", "").toLowerCase();
                            String proposalNameCNStr = proposalNameCN.replace("（", "(").replace("）", ")").replace(" ", "").toLowerCase();

                            if ((!currentNameCNStr.equals(proposalNameCNStr))) {

                                sense = true;

                            }
                        }
                    }
                    if (sense || StringUtils.isEmpty(dealerSectorContractgroups)) { //合同号为空或者currentname跟proposalname两个值不一样就再走New  application业务场景
                        BasicContract basicContract = new BasicContract();
                        basicContract.setPriority("4");
                        basicContract.setLimittype(cb);
                        basicContract.setSector(sector);
                        al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同New application

                        //对应得flag变成false
                        DealerSectorLimitflag flag = new DealerSectorLimitflag();
                        flag.setDealername(Dealername);
                        flag.setSector(sector);
                        DealerSectorLimitflag oldBean = new DealerSectorLimitflag();
                        List<DealerSectorLimitflag> dealerSectorLimitflags = dealerSectorLimitflagService.selectDealerSectorLimitflagList(flag);
                        if(StringUtils.isNotEmpty(dealerSectorLimitflags)){
                            oldBean =  dealerSectorLimitflags.get(0);
                        }
                        flag.setCbflag("false");
                        dealerSectorLimitflagService.updateDealerSectorLimitflag(flag);
                        annualReviewyService.saveDbLog("3","修改合同标识信息",null,instanceId,oldBean,flag,"CRO确认");
                    } else {
                        CreditCondition cc = new CreditCondition();
                        cc.setDealername(Dealername);
                        cc.setSector(sector);
                        cc.setLimittype(alacFour.getLimitType());
                        cc.setInstanceid(instanceId);
                        CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
                        WholesalePerformanceCurrently wpc = new WholesalePerformanceCurrently();
                        wpc.setDealername(Dealername);
                        wpc.setSector(sector);
                        wpc.setLimitType(alacFour.getLimitType());
                        wpc.setInstanceId(instanceId);
                        List<WholesalePerformanceCurrently> wholesalePerformanceCurrently = wholesalePerformanceCurrentlyService.selectWholesalePerformanceCurrentlyList(wpc);
                        String a = "";
                        if (StringUtils.isNotEmpty(wholesalePerformanceCurrently)) {
                            a = wholesalePerformanceCurrently.get(0).getExpiryDate();
                        }
                        //CreditCondition表的日期不等于WholesalePerformanceCurrently表的日期，就再出Temp Limit这个合同
                        String dateToStr = "";
                        if (StringUtils.isNotNull(creditCondition.getExpireddate())) {
                            Date expireddate = creditCondition.getExpireddate();
                            dateToStr = DateUtils.parseDateToStr("yyyy/MM/dd", expireddate);
                        }
                        if (StringUtils.isNull(alacFour.getApprovedLimit())) {
                            alacFour.setApprovedLimit(new Long(0));
                        }
                        if (StringUtils.isEmpty(alacFour.getApprovedCashDeposit())) {
                            alacFour.setApprovedCashDeposit("0");
                        }
                        //判断表h_approved_limit_and_condition里的current跟proposal不一致的时候或者CreditCondition表的日期不等于WholesalePerformanceCurrently表的日期
                        if ((!alacFour.getApprovedLimit().equals(alacFour.getProposalLimit())) || (!alacFour.getApprovedCashDeposit().equals(alacFour.getProposalCashDeposit())) || !dateToStr.equals(a)) {
                            BasicContract basicContract = new BasicContract();
                            basicContract.setPriority("2");
                            basicContract.setLimittype(cb);
                            basicContract.setSector(sector);
                            al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Limit amount/ratio change
                        }
                    }
                }
            }

            if(cb.equals("CB one-off fleet")) {
                if (dealerSectorLimitflagTwo.getCbflag().equals("true") && (isAR || changNameFlag || isTermination)) {
                    BasicContract basicContract = new BasicContract();
                    basicContract.setPriority("4");
                    basicContract.setLimittype(cb);
                    basicContract.setSector(sector);
                    al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同New application
                    //对应得flag变成false
                    DealerSectorLimitflag flag = new DealerSectorLimitflag();
                    flag.setDealername(Dealername);
                    flag.setSector(sector);
                    DealerSectorLimitflag oldBean = new DealerSectorLimitflag();
                    List<DealerSectorLimitflag> dealerSectorLimitflags = dealerSectorLimitflagService.selectDealerSectorLimitflagList(flag);
                    if(StringUtils.isNotEmpty(dealerSectorLimitflags)){
                        oldBean =  dealerSectorLimitflags.get(0);
                    }
                    flag.setCbflag("false");
                    dealerSectorLimitflagService.updateDealerSectorLimitflag(flag);
                    annualReviewyService.saveDbLog("3","修改合同标识信息",null,instanceId,oldBean,flag,"CRO确认");

                } else {
                    //否则就判断h_dealer_sector_contractgroup表里的合同组里有没有《CB改装车协议(循环)》或者大客户--->
                    DealerSectorContractgroup dealerSectorContractgroup = new DealerSectorContractgroup();
                    dealerSectorContractgroup.setDealername(Dealername);
                    dealerSectorContractgroup.setSector(sector);
                    dealerSectorContractgroup.setContractname("CB 改装车大客户延期补充协议");//不知道合同号，先用合同名称测
                    List<DealerSectorContractgroup> dealerSectorContractgroups = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                    //TODO 如果是CB流程的话，这里是否还是判断改装车，因为CB流程出的是大客户
//                if (StringUtils.isEmpty(dealerSectorContractgroups)) {
                    boolean sense = false;
                    //取对应流程的表的全部数据，判断currentname跟proposalname是否一致，只要两个值不一样
                    Securities guaranteeInformation = new Securities();
                    guaranteeInformation.setInstanceId(instanceId);
                    guaranteeInformation.setDealername(Dealername);
                    List<Securities> guaranteeInformations = securitiesMapper.selectSecuritiesListTypeIsnotnull(guaranteeInformation);
                    if (StringUtils.isNotEmpty(guaranteeInformations)) {
                        for (Securities gif : guaranteeInformations) {
                            if (StringUtils.isEmpty(gif.getCurrentNameCN())) {
                                gif.setCurrentNameCN("");
                            }
                            if (StringUtils.isEmpty(gif.getProposalNameCN())) {
                                gif.setProposalNameCN("");
                            }
                            String currentNameCN = gif.getCurrentNameCN();
                            String proposalNameCN = gif.getProposalNameCN();
                            String currentNameCNStr = currentNameCN.replace("（", "(").replace("）", ")").replace(" ", "").toLowerCase();
                            String proposalNameCNStr = proposalNameCN.replace("（", "(").replace("）", ")").replace(" ", "").toLowerCase();

                            if ((!currentNameCNStr.equals(proposalNameCNStr))) {

                                sense = true;

                            }
                        }
                    }
                    if (sense || StringUtils.isEmpty(dealerSectorContractgroups)) { //合同号为空或者currentname跟proposalname两个值不一样就再走New  application业务场景
                        BasicContract basicContract = new BasicContract();
                        basicContract.setPriority("4");
                        basicContract.setLimittype(cb);
                        basicContract.setSector(sector);
                        al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同New application

                        //对应得flag变成false
                        DealerSectorLimitflag flag = new DealerSectorLimitflag();
                        flag.setDealername(Dealername);
                        flag.setSector(sector);
                        DealerSectorLimitflag oldBean = new DealerSectorLimitflag();
                        List<DealerSectorLimitflag> dealerSectorLimitflags = dealerSectorLimitflagService.selectDealerSectorLimitflagList(flag);
                        if(StringUtils.isNotEmpty(dealerSectorLimitflags)){
                            oldBean =  dealerSectorLimitflags.get(0);
                        }
                        flag.setCbflag("false");
                        dealerSectorLimitflagService.updateDealerSectorLimitflag(flag);
                        annualReviewyService.saveDbLog("3","修改合同标识信息",null,instanceId,oldBean,flag,"CRO确认");
                    } else {
                        CreditCondition cc = new CreditCondition();
                        cc.setDealername(Dealername);
                        cc.setSector(sector);
                        cc.setLimittype(alacFour.getLimitType());
                        cc.setInstanceid(instanceId);
                        CreditCondition creditCondition = creditConditionService.selectCreditConditionList(cc).get(0);
                        WholesalePerformanceCurrently wpc = new WholesalePerformanceCurrently();
                        wpc.setDealername(Dealername);
                        wpc.setSector(sector);
                        wpc.setLimitType(alacFour.getLimitType());
                        wpc.setInstanceId(instanceId);
                        List<WholesalePerformanceCurrently> wholesalePerformanceCurrently = wholesalePerformanceCurrentlyService.selectWholesalePerformanceCurrentlyList(wpc);
                        String a = "";
                        if (StringUtils.isNotEmpty(wholesalePerformanceCurrently)) {
                            a = wholesalePerformanceCurrently.get(0).getExpiryDate();
                        }
                        //CreditCondition表的日期不等于WholesalePerformanceCurrently表的日期，就再出Temp Limit这个合同
                        String dateToStr = "";
                        if (StringUtils.isNotNull(creditCondition.getExpireddate())) {
                            Date expireddate = creditCondition.getExpireddate();
                            dateToStr = DateUtils.parseDateToStr("yyyy/MM/dd", expireddate);
                        }
                        if (StringUtils.isNull(alacFour.getApprovedLimit())) {
                            alacFour.setApprovedLimit(new Long(0));
                        }
                        if (StringUtils.isEmpty(alacFour.getApprovedCashDeposit())) {
                            alacFour.setApprovedCashDeposit("0");
                        }
                        //判断表h_approved_limit_and_condition里的current跟proposal不一致的时候或者CreditCondition表的日期不等于WholesalePerformanceCurrently表的日期
                        if ((!alacFour.getApprovedLimit().equals(alacFour.getProposalLimit())) || (!alacFour.getApprovedCashDeposit().equals(alacFour.getProposalCashDeposit())) || !dateToStr.equals(a)) {
                            BasicContract basicContract = new BasicContract();
                            basicContract.setPriority("2");
                            basicContract.setLimittype(cb);
                            basicContract.setSector(sector);
                            al.addAll(basicContractService.selectBasicContractList(basicContract));//出这个合同Limit amount/ratio change
                        }
                    }
                }
            }
        }
//        if(StringUtils.isEmpty(al)){
//            throw new BaseException("没有触发能生成合同的场景！");
//        }
    return al;
    }

    @Override
    @Transactional
    public int contractnew(Map<String, Object> resultMap){
        String instanceId = (String) resultMap.get("instanceId");
        if(StringUtils.isEmpty(instanceId)){
            throw new BaseException("instanceId不能为空");
        }
        //定义编号格式001
        DecimalFormat decimalFormat = new DecimalFormat("000");
        ProposalByCommericalAndMarketing approvedLimitAndCondition = new ProposalByCommericalAndMarketing();
        approvedLimitAndCondition.setInstanceId(instanceId);
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditions = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingListgroupby(approvedLimitAndCondition);
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditionsTemp = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingListgroupbyThree(approvedLimitAndCondition);
        List<ProposalByCommericalAndMarketing> approvedLimitAndConditionsTempByDemo = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingListgroupbyThree1(approvedLimitAndCondition);
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        HashMap<String, String> stringStringHashMapByDemo = new HashMap<>();
        if(approvedLimitAndConditionsTemp!=null && approvedLimitAndConditionsTemp.size()>0 ){
            Map<String, List<ProposalByCommericalAndMarketing>> collect1 = approvedLimitAndConditionsTemp.stream().collect(Collectors.groupingBy(ProposalByCommericalAndMarketing::getDealername));
            for (String key : collect1.keySet()) {
                HChangeLegalPerson hChangeLegalPerson = new HChangeLegalPerson();
                hChangeLegalPerson.setDealerName(key);
                hChangeLegalPerson.setIsSuccess(0);
                List<HChangeLegalPerson> hChangeLegalPeople = changeLegalPersonMapper.selectHChangeLegalPersonList(hChangeLegalPerson);
                if(hChangeLegalPeople !=null && hChangeLegalPeople.size()>0){
                    stringStringHashMap.put(key,"true");
                }
            }
        }
        if(approvedLimitAndConditionsTempByDemo!=null && approvedLimitAndConditionsTempByDemo.size()>0 ){
            Map<String, List<ProposalByCommericalAndMarketing>> collect1 = approvedLimitAndConditionsTempByDemo.stream().collect(Collectors.groupingBy(ProposalByCommericalAndMarketing::getDealername));
            for (String key : collect1.keySet()) {
                HChangeLegalPerson hChangeLegalPerson = new HChangeLegalPerson();
                hChangeLegalPerson.setDealerName(key);
                hChangeLegalPerson.setIsSuccess(0);
                List<HChangeLegalPerson> hChangeLegalPeople = changeLegalPersonMapper.selectHChangeLegalPersonList(hChangeLegalPerson);
                if(hChangeLegalPeople !=null && hChangeLegalPeople.size()>0){
                    stringStringHashMapByDemo.put(key,"true");
                }
            }
        }
        System.out.println("DEMO"+stringStringHashMapByDemo);
        for(ProposalByCommericalAndMarketing applac : approvedLimitAndConditions) {
            Map<String, Object> map = new HashMap<>();
            map.put("Dealername", applac.getDealername());
            map.put("sector", applac.getSector());
            map.put("instanceId", instanceId);
            List<BasicContract>  basicContracts = null;
            basicContracts = this.matchTheContractNew(map);
            System.out.println("生成合同结束，list为"+basicContracts);
            System.out.println("生成合同结束，applac为"+applac);
            //查询此次是否是dct场景，是的话，主合同需要以试乘试驾车贷款合同为查询最大合同号
            if (StringUtils.isNotEmpty(basicContracts) && basicContracts.get(0).getLimittype().equals("Normal")) {
                if(stringStringHashMap.get(applac.getDealername())!=null){
                    boolean fjfive =false;
                    for (BasicContract basicContract : basicContracts) {
                        if(basicContract.getContractname().equals("人民币循环贷款合同附件五") || basicContract.getContractname().equals("人民币循环贷款合同")){
                            fjfive = true;
                            HChangeLegalPerson changeLegalPerson = new HChangeLegalPerson();
                            changeLegalPerson.setDealerName(applac.getDealername());
                            changeLegalPerson.setIsSuccess(0);
                            List<HChangeLegalPerson> changeLegalPersonS = changeLegalPersonMapper.selectHChangeLegalPersonList(changeLegalPerson);
                            if(changeLegalPersonS !=null && changeLegalPersonS.size()>0) {
                                for (HChangeLegalPerson person : changeLegalPersonS) {
                                    HChangeLegalPerson hChangeLegalPerson = new HChangeLegalPerson();
                                    BeanUtils.copyProperties(person, hChangeLegalPerson);
                                    person.setUpdateTime(new Date());
                                    person.setCandidateNo(instanceId);
                                    person.setIsSuccess(1);
                                    changeLegalPersonMapper.updateHChangeLegalPerson(person);
                                    annualReviewyService.saveDbLog("3","修改法人变更记录",null,instanceId,hChangeLegalPerson,person,"CRO确认");
                                }
                            }
                            break;
                        }
                    }
                    if(!fjfive){
                        HChangeLegalPerson changeLegalPerson = new HChangeLegalPerson();
                        changeLegalPerson.setDealerName(applac.getDealername());
                        changeLegalPerson.setIsSuccess(0);
                        List<HChangeLegalPerson> changeLegalPersonS = changeLegalPersonMapper.selectHChangeLegalPersonList(changeLegalPerson);
                        if(changeLegalPersonS !=null && changeLegalPersonS.size()>0) {
                            for (HChangeLegalPerson person : changeLegalPersonS) {
                                HChangeLegalPerson hChangeLegalPerson = new HChangeLegalPerson();
                                BeanUtils.copyProperties(person, hChangeLegalPerson);
                                person.setUpdateTime(new Date());
                                person.setCandidateNo(instanceId);
                                person.setIsSuccess(1);
                                changeLegalPersonMapper.updateHChangeLegalPerson(person);
                                annualReviewyService.saveDbLog("3","修改法人变更记录",null,instanceId,hChangeLegalPerson,person,"CRO确认");
                            }
                        }
                        //没出附件5 但是要增加附件5
                        Map<String, Map<String, List<BasicContract>>> collect = basicContracts.stream().collect(Collectors.groupingBy(BasicContract::getSector, Collectors.groupingBy(BasicContract::getLimittype)));
                        for (String key : collect.keySet()) {
                            Map<String, List<BasicContract>> stringListMap = collect.get(key);
                            for (String key2 : stringListMap.keySet()) {
                                if(key2.equals("Normal")){
                                    BasicContract basicContract = new BasicContract();
                                    basicContract.setContractname("人民币循环贷款合同附件五");
                                    basicContract.setSector(key);
                                    basicContract.setLimittype(key2);
                                    basicContract.setContractlocation("/profile/template/"+key+"/人民币循环贷款合同附件五.docx");
                                    basicContract.setPriority(basicContracts.get(0).getPriority());
                                    basicContracts.add(basicContract);
                                }

                            }
                        }
                    }
                }
            }
            if (StringUtils.isNotEmpty(basicContracts) && basicContracts.get(0).getLimittype().toUpperCase().equals("DEMO") && (applac.getSector().toUpperCase().equals("ALFA ROMEO")|| applac.getSector().toUpperCase().equals("DS") || applac.getSector().toUpperCase().equals("CHRYSLER"))) {
                System.out.println("进来了"+applac);
                if(stringStringHashMapByDemo.get(applac.getDealername())!=null){
                    boolean fjfive2 =false;
                    for (BasicContract basicContract : basicContracts) {
                        if(basicContract.getContractname().equals("试乘试驾车贷款合同附件三") || basicContract.getContractname().equals("试乘试驾车贷款合同")){
                            System.out.println("有附件三");
                            fjfive2 = true;
                            HChangeLegalPerson changeLegalPerson = new HChangeLegalPerson();
                            changeLegalPerson.setDealerName(applac.getDealername());
                            changeLegalPerson.setIsSuccess(0);
                            List<HChangeLegalPerson> changeLegalPersonS = changeLegalPersonMapper.selectHChangeLegalPersonList(changeLegalPerson);
                            if(changeLegalPersonS !=null && changeLegalPersonS.size()>0) {
                                for (HChangeLegalPerson person : changeLegalPersonS) {
                                    HChangeLegalPerson hChangeLegalPerson = new HChangeLegalPerson();
                                    BeanUtils.copyProperties(person, hChangeLegalPerson);
                                    person.setUpdateTime(new Date());
                                    person.setCandidateNo(instanceId);
                                    person.setIsSuccess(1);
                                    changeLegalPersonMapper.updateHChangeLegalPerson(person);
                                    annualReviewyService.saveDbLog("3","修改法人变更记录",null,instanceId,hChangeLegalPerson,person,"CRO确认");
                                }
                            }
                            break;
                        }
                    }
                    if(!fjfive2){
                        HChangeLegalPerson changeLegalPerson = new HChangeLegalPerson();
                        changeLegalPerson.setDealerName(applac.getDealername());
                        changeLegalPerson.setIsSuccess(0);
                        List<HChangeLegalPerson> changeLegalPersonS = changeLegalPersonMapper.selectHChangeLegalPersonList(changeLegalPerson);
                        if(changeLegalPersonS !=null && changeLegalPersonS.size()>0) {
                            for (HChangeLegalPerson person : changeLegalPersonS) {
                                HChangeLegalPerson hChangeLegalPerson = new HChangeLegalPerson();
                                BeanUtils.copyProperties(person, hChangeLegalPerson);
                                person.setUpdateTime(new Date());
                                person.setCandidateNo(instanceId);
                                person.setIsSuccess(1);
                                changeLegalPersonMapper.updateHChangeLegalPerson(person);
                                annualReviewyService.saveDbLog("3","修改法人变更记录",null,instanceId,hChangeLegalPerson,person,"CRO确认");
                            }
                        }
                        //没出附件三 但是要增加附件三
                        Map<String, Map<String, List<BasicContract>>> collect = basicContracts.stream().collect(Collectors.groupingBy(BasicContract::getSector, Collectors.groupingBy(BasicContract::getLimittype)));
                        for (String key : collect.keySet()) {
                            Map<String, List<BasicContract>> stringListMap = collect.get(key);
                            for (String key2 : stringListMap.keySet()) {
                                if(key2.toUpperCase().equals("DEMO")){
                                    BasicContract basicContract = new BasicContract();
                                    basicContract.setContractname("试乘试驾车贷款合同附件三");
                                    basicContract.setSector(key);
                                    basicContract.setLimittype(key2);
                                    if(key.toUpperCase().equals("ALFA ROMEO")){
                                        basicContract.setContractlocation("/profile/template/Alfa Romeo/试乘试驾车贷款合同附件三.docx");
                                    }
                                    if(key.toUpperCase().equals("DS")){
                                        basicContract.setContractlocation("/profile/template/DS/试乘试驾车贷款合同附件三.docx");
                                    }
                                    if(key.toUpperCase().equals("CHRYSLER")){
                                        basicContract.setContractlocation("/profile/template/Chrysler/试乘试驾车贷款合同附件三.docx");
                                    }
                                    basicContract.setPriority(basicContracts.get(0).getPriority());
                                    basicContracts.add(basicContract);
                                }

                            }
                        }
                    }
                }
            }
            //判断一下这出的合同里如果该经销商没有担保人，就不出个人保函，如果没有担保企业，就不出企业保函
            //查该经销商下对应得担保人和担保机构
            Securities securities = new Securities();
            securities.setInstanceId(instanceId);
            securities.setDealername(applac.getDealername());
            List<Securities> securitiesList = securitiesMapper.selectSecuritiesListTypeIsnotnull(securities);
            StringBuilder stringBuilder = new StringBuilder();
            List<String> objects = new ArrayList<>();
            if(StringUtils.isNotEmpty(securitiesList)){
                for(Securities securities1 : securitiesList){
                    if((!StringUtils.isEmpty(securities1.getProposalNameCN())) && (!StringUtils.isEmpty(securities1.getProposalNameEN()))){
                        stringBuilder.append(securities1.getGuaranteeType()).append(",");
                    }
                }
            }
            if (StringUtils.isNotEmpty(stringBuilder)){
                String s = (stringBuilder.substring(0, stringBuilder.length() - 1)).toString();
                String[] split = s.split(",");
                for(String sp : split){
                    objects.add(sp);
                }
                List<String> objects1 = objects.stream().distinct().collect(Collectors.toList());
                //当这个集合只有一条的时候，就看类型是个人还是企业，然后删除
                if(objects1.size() ==1){
                    if(objects1.get(0).equals("personal")){
                        //使用迭代器删除集合中某一元素值
                        Iterator<BasicContract> iterator = basicContracts.iterator();
                        while(iterator.hasNext()) {
                            BasicContract next = iterator.next();
                            String name = next.getContractname();
                            if (name.equals("企业保函") || name.equals("试驾车企业保函")) {
                                iterator.remove();
                            }
                        }
                    }
                    if(objects1.get(0).equals("corporate")){
                        //使用迭代器删除集合中某一元素值
                        Iterator<BasicContract> iterator = basicContracts.iterator();
                        while(iterator.hasNext()) {
                            BasicContract next = iterator.next();
                            String name = next.getContractname();
                            if (name.equals("个人保函") || name.equals("试驾车个人保函")) {
                                iterator.remove();
                            }
                        }
                    }
                }else if (objects1.size() ==0){
                    //假如什么担保人担保企业都没有，那就都删了,查肯定查不到数据
                    //使用迭代器删除集合中某一元素值
                    Iterator<BasicContract> iterator = basicContracts.iterator();
                    while(iterator.hasNext()) {
                        BasicContract next = iterator.next();
                        String name = next.getContractname();
                        if (name.equals("个人保函") || name.equals("试驾车个人保函") || name.equals("企业保函") || name.equals("试驾车企业保函")) {
                            iterator.remove();
                        }
                    }
                }
            }else{
                Iterator<BasicContract> iterator = basicContracts.iterator();
                while(iterator.hasNext()) {
                    BasicContract next = iterator.next();
                    String name = next.getContractname();
                    if (name.equals("个人保函") || name.equals("试驾车个人保函") || name.equals("企业保函") || name.equals("试驾车企业保函")) {
                        iterator.remove();
                    }
                }
            }

            //如果没有动额度跟额度比例，那么就不需要出三方附件二
//            if(StringUtils.isNull(applac.getApprovedLimit())){
//                applac.setApprovedLimit(new Long(0));
//            }
//            if(StringUtils.isEmpty(applac.getApprovedCashDeposit())){
//                applac.setApprovedCashDeposit("0");
//            }
//            if(applac.getApprovedLimit().equals(applac.getProposalLimit()) && applac.getApprovedCashDeposit().equals(applac.getProposalCashDeposit())){
//                //使用迭代器删除集合中某一元素值
//                Iterator<BasicContract> iterator = basicContracts.iterator();
//                while(iterator.hasNext()) {
//                    BasicContract next = iterator.next();
//                    String name = next.getContractname();
//                    if (name.equals("三方合同-附件二 贷款额度及保证金通知书")) {
//                        iterator.remove();
//                    }
//                }
//            }
            //把生成的合同数据全部存入dealercode_contract表中，以便后续回看历史记录
            if (StringUtils.isNotEmpty(basicContracts)) {

                //这里倒叙排序
                for (BasicContract basicContract : basicContracts) {
                    if(basicContract.getContractname()!=null){
                        //查询排序
                        Integer sort = NameSort(basicContract.getContractname(),basicContract.getLimittype());
                        basicContract.setSort(sort);
                    }
                }
                //循环结束需要排序
                basicContracts.sort(Comparator.comparingInt(BasicContract::getSort));
                for (BasicContract basicContract : basicContracts) {
                    System.out.println("合同排序为"+basicContract.getContractname());
                }
                DealercodeContract dealercodeContract = new DealercodeContract();
                dealercodeContract.setDealerNameCN(applac.getDealername());
                dealercodeContract.setSector(applac.getSector());
                dealercodeContract.setInstanceId(instanceId);
                //提前把主合同号查出来，这样在循环的时候修改数据就不会影响下一次循环的取值，否则下一次取得值就是修改以后的了
                DealerSectorContractgroup dealerSectorContractgroup = new DealerSectorContractgroup();
                dealerSectorContractgroup.setDealername(applac.getDealername());
                dealerSectorContractgroup.setSector(applac.getSector());
                dealerSectorContractgroup.setContractname("人民币循环贷款合同");
                List<DealerSectorContractgroup> dealerSectorContractgroups = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                dealerSectorContractgroup.setContractname("试乘试驾车贷款合同");
                List<DealerSectorContractgroup> dealerSectorContractgroupsDemo = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                dealerSectorContractgroup.setContractname("CB 改装车协议（循环）");
                List<DealerSectorContractgroup> dealerSectorContractgroupsCbRevolving = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                dealerSectorContractgroup.setContractname("CB 大客户协议（一次性额度）");
                List<DealerSectorContractgroup> dealerSectorContractgroupsCboneoffFleet = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);

                //查询之前是不是termination
                DealerSectorLimitflag dealerSectorLimitflag = new DealerSectorLimitflag();
                dealerSectorLimitflag.setDealername(applac.getDealername());
                dealerSectorLimitflag.setSector(applac.getSector());
                boolean  isTermination = false;
                List<DealerSectorLimitflag> dealerSectorLimitflags = dealerSectorLimitflagService.selectDealerSectorLimitflagList(dealerSectorLimitflag);
                for (DealerSectorLimitflag sectorLimitflag : dealerSectorLimitflags) {
                    if(sectorLimitflag.getIsTermination()!=null && sectorLimitflag.getIsTermination() ==1){
                        isTermination = true;
                        //改回去
                        sectorLimitflag.setIsTermination(0);
                        dealerSectorLimitflagService.updateDealerSectorLimitflag(sectorLimitflag);
                        break;
                    }
                }

                String contractNoMain = "";
                //获取当前年份
                String currentYear = DateUtils.getCurrentYear();
                String substring1 = currentYear.substring(2);
                //查询 1.判断是不是Termination
                if(isTermination){
                    String maxNumber = dealerSectorContractgroupMapper.selectMaxNumberByDealerCode();
                    //查历史合同里的最大年份
                    DealerSectorContractgroup ContractTemp = new DealerSectorContractgroup();
                    ContractTemp.setContractname("人民币循环贷款合同");
                    String maxNian = dealerSectorContractgroupMapper.selectMaxNian(ContractTemp);
                    Map<String, Object> maxMap = new HashMap<>();
                    maxMap.put("dealerCode", applac.getDealerCode());
                    maxMap.put("contractMax", Integer.valueOf(maxNumber)+1);
                    maxMap.put("status",0);
                    maxMap.put("dealerName",applac.getDealername());
                    maxMap.put("sector",applac.getSector());
                    String format = decimalFormat.format(Integer.valueOf(maxNumber)+1);
                    //调用方法拼出主合同号
                    if(!substring1.equals(maxNian)){
                        //说明要从001开始
                        maxMap.put("contractMax", 1);
                        format  = decimalFormat.format(1);
                        //修改状态
                        dealerSectorContractgroupMapper.updateDealerSectorContract(maxMap);
                    }
                    String f = maincontractno(applac.getDealerCode(), "F", instanceId, format, "", applac.getDealername(),"");
                    maxMap.put("contractNo",f);
                    contractNoMain = f ;
                    dealerSectorContractgroupMapper.insertDealerSectorContractMax(maxMap);
                }else{
                    if(StringUtils.isEmpty(dealerSectorContractgroups)){
                        //说明没有人民币主合同，去查询max表
                        String contractNo = dealerSectorContractgroupMapper.selectNumberByDealerCode(applac.getDealerCode());
                        if(StringUtils.isNotEmpty(contractNo)){
                            //说明有历史 延用
                            contractNoMain = contractNo;
                        }else{
                            String maxNumber = dealerSectorContractgroupMapper.selectMaxNumberByDealerCode();
                            DealerSectorContractgroup ContractTemp = new DealerSectorContractgroup();
                            ContractTemp.setContractname("人民币循环贷款合同");
                            String maxNian = dealerSectorContractgroupMapper.selectMaxNian(ContractTemp);
                            Map<String, Object> maxMap = new HashMap<>();
                            maxMap.put("dealerCode", applac.getDealerCode());
                            maxMap.put("contractMax", Integer.valueOf(maxNumber)+1);
                            maxMap.put("status",0);
                            maxMap.put("dealerName",applac.getDealername());
                            maxMap.put("sector",applac.getSector());
                            String format = decimalFormat.format(Integer.valueOf(maxNumber)+1);
                            //调用方法拼出主合同号
                            if(!substring1.equals(maxNian)){
                                //说明要从001开始
                                maxMap.put("contractMax", 1);
                                format  = decimalFormat.format(1);
                                //修改状态
                                dealerSectorContractgroupMapper.updateDealerSectorContract(maxMap);
                            }
                            String f = maincontractno(applac.getDealerCode(), "F", instanceId, format, "", applac.getDealername(),"");
                            maxMap.put("contractNo",f);
                            contractNoMain = f ;
                            dealerSectorContractgroupMapper.insertDealerSectorContractMax(maxMap);
                        }
                    }else{
                        contractNoMain = dealerSectorContractgroups.get(0).getContractnumber();
                    }
                }

                dealerSectorContractgroup.setContractname("人民币循环贷款合同");
                //String maxNumber = dealerSectorContractgroupMapper.selectMaxNumber(dealerSectorContractgroup);
                //查历史合同里的最大年份
                // String maxNian = dealerSectorContractgroupMapper.selectMaxNian(dealerSectorContractgroup);
                //在循环之前取附件二当常量，因为循环里会进行新数据替换操作，所以提前取出来免得被影响
                DealerSectorContractgroup dealerSectorContractgroupTwo = new DealerSectorContractgroup();
                dealerSectorContractgroupTwo.setDealername(applac.getDealername());
                dealerSectorContractgroupTwo.setSector(applac.getSector());
                dealerSectorContractgroupTwo.setContractname("人民币循环贷款合同附件二");
                List<DealerSectorContractgroup> dealerSectorContractgroupsTwo = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroupTwo);
                //提前把附件二序列号取出来，免得在循环里因为新增一直变动
                String SerialNumberNormal = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroupTwo);
                //在循环之前取DEMO得附件一当常量，因为循环里会进行新数据替换操作，所以提前取出来免得被影响
                DealerSectorContractgroup dealerSectorContractgroupDemoOne = new DealerSectorContractgroup();
                dealerSectorContractgroupDemoOne.setDealername(applac.getDealername());
                dealerSectorContractgroupDemoOne.setSector(applac.getSector());
                dealerSectorContractgroupDemoOne.setContractname("试乘试驾车贷款合同附件一");
                List<DealerSectorContractgroup> dealerSectorContractgroupsDemoOne = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroupDemoOne);
                //在循环之前取CB大客户得附件一当常量，因为循环里会进行新数据替换操作，所以提前取出来免得被影响
                DealerSectorContractgroup dealerSectorContractgroupCBOne = new DealerSectorContractgroup();
                dealerSectorContractgroupCBOne.setDealername(applac.getDealername());
                dealerSectorContractgroupCBOne.setSector(applac.getSector());
                dealerSectorContractgroupCBOne.setContractname("CB 大客户延期还款产品担保附件一");
                List<DealerSectorContractgroup> dealerSectorContractgroupsCBOne = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroupCBOne);
                //在循环之前把新的CB合同当常量取出来，因为循环里会进行新数据替换操作，所以提前取出来免得被影响
                DealerSectorContractgroup dealerSectorContractgroupCBnew = new DealerSectorContractgroup();
                dealerSectorContractgroupCBnew.setDealername(applac.getDealername());
                dealerSectorContractgroupCBnew.setSector(applac.getSector());
                dealerSectorContractgroupCBnew.setContractname("CB 改装车大客户延期补充协议");
                List<DealerSectorContractgroup> dealerSectorContractgroupsCBnew = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroupCBnew);
                //提前把附件一序列号取出来，免得在循环里因为新增一直变动
                String SerialNumberDemo = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroupDemoOne);
                //提前把CB附件一序列号取出来，免得在循环里因为新增一直变动
                String SerialNumberCB = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroupCBOne);
                //提前把新CB序列号取出来，免得在循环里因为新增一直变动
                String SerialNumberCBnew = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroupCBnew);
                //判断下这出的全部合同里包不包含人民币循环贷款主合同，如果包含那主合同号就会+1，这样一来其他的合同基于F主合同也要编号+1


                for (BasicContract bc : basicContracts) {
                    System.out.println("合同名称啊123"+bc.getContractname());
                    dealercodeContract.setContract(null);
                    dealercodeContract.setContractName(bc.getContractname());
                    dealercodeContract.setContractLocation(bc.getContractlocation());
                    //合同表的limittype.为CB的跟三方接口得到的CB不一样，所以这里跟三方CB统一，避免后面用这个值查其他表的limittype查不到
                    if(bc.getLimittype().equals("CB Revolving") || bc.getLimittype().equals("CB one-off fleet")){
                        bc.setLimittype("CB");
                    }
                    dealercodeContract.setLimitType(bc.getLimittype());
                    dealercodeContract.setPriority(bc.getPriority());
                    //其中个别合同需要生成合同号
                    //调用方法获取dealercode
                    String dealercodelist = dealercodelist(instanceId, applac.getDealername(), applac.getSector());
                    //有历史合同数据就修改历史合同，没有就新增合同数据
                    DealerSectorContractgroup dealerSectorContractgroupadd = new DealerSectorContractgroup();
                    dealerSectorContractgroupadd.setDealername(applac.getDealername());
                    dealerSectorContractgroupadd.setSector(applac.getSector());
                    dealerSectorContractgroupadd.setDealerCode(dealercodelist);
                    //查历史合同数据，如果该合同在历史合同里存在就取合同号进行递增+1

                    //话就替换下，没有的话就新生成
                    if (bc.getContractname().equals("人民币循环贷款合同")) {
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups) && !isTermination){
                            //继承主合同号
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String f =contracthistory;
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                            }
                        }else {
                            dealercodeContract.setContract(contractNoMain);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(contractNoMain);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                            }
                        }

                        //主合同内容里包含了附件合同号，所以附件也要生成
                        DealercodeContract dealercodeContract1 = new DealercodeContract();
                        dealercodeContract1.setDealerNameCN(applac.getDealername());
                        dealercodeContract1.setSector(applac.getSector());
                        dealercodeContract1.setInstanceId(instanceId);
                        dealercodeContract1.setContractName("人民币循环贷款合同附件二");
                        dealercodeContract1.setLimitType(bc.getLimittype());
                        dealercodeContract1.setPriority(bc.getPriority());
                        dealerSectorContractgroup.setContractname("人民币循环贷款合同附件二");
                        List<DealerSectorContractgroup> dealerSectorContractgroupsAccessory = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                        String count = null;
                        if(StringUtils.isEmpty(dealerSectorContractgroupsAccessory) && StringUtils.isEmpty(dealerSectorContractgroups)){
                            count = "1";
                        }else if(StringUtils.isEmpty(dealerSectorContractgroupsAccessory) && StringUtils.isNotEmpty(dealerSectorContractgroups)){
                            count = "2";
                        }else {
                            count = String.valueOf(Double.valueOf(SerialNumberNormal).intValue());
                        }
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination ){
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String f =  contracthistory +"-2"+"-"+count;
                            dealercodeContract1.setContract(f);
                            dealerSectorContractgroupadd.setContractname("人民币循环贷款合同附件二");
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                        }else {
                            if(isTermination){
                                count = "1";
                            }
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f =  contractNoMain +"-2";
                            }else{
                                f =  contractNoMain +"-2"+"-"+count;
                            }
                            dealercodeContract1.setContract(f);
                            dealerSectorContractgroupadd.setContractname("人民币循环贷款合同附件二");
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                        }
                        dealercodeContractService.insertDealercodeContract(dealercodeContract1);
                        annualReviewyService.saveDbLog("1","新增合同信息",null,instanceId,null,dealercodeContract1,"CRO确认");



                        //主合同内容里包含了附件合同号，所以附件也要生成
                        DealercodeContract dealercodeContract2 = new DealercodeContract();
                        dealercodeContract2.setDealerNameCN(applac.getDealername());
                        dealercodeContract2.setSector(applac.getSector());
                        dealercodeContract2.setInstanceId(instanceId);
                        dealercodeContract2.setContractName("人民币循环贷款合同附件四");
                        dealercodeContract2.setLimitType(bc.getLimittype());
                        dealercodeContract2.setPriority(bc.getPriority());
                        if(StringUtils.isEmpty(dealerSectorContractgroupsTwo) && StringUtils.isEmpty(dealerSectorContractgroups)){
                            count = "1";
                        }else if(StringUtils.isEmpty(dealerSectorContractgroupsTwo) && StringUtils.isNotEmpty(dealerSectorContractgroups)){
                            count = "2";
                        }else {
                            count = String.valueOf(Double.valueOf(SerialNumberNormal).intValue());
                        }
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)   && !isTermination ){
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String f =  contracthistory +"-4"+"-"+count;
                            dealercodeContract2.setContract(f);
                            dealerSectorContractgroupadd.setContractname("人民币循环贷款合同附件四");
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                        }else {
                            if(isTermination){
                                count = "1";
                            }
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f =  contractNoMain +"-4";
                            }else{
                                f =  contractNoMain +"-4"+"-"+count;
                            }
                            dealercodeContract2.setContract(f);
                            dealerSectorContractgroupadd.setContractname("人民币循环贷款合同附件四");
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                        }
                        dealercodeContractService.insertDealercodeContract(dealercodeContract2);
                        annualReviewyService.saveDbLog("1","新增合同信息",null,instanceId,null,dealercodeContract2,"CRO确认");


                        DealercodeContract dealercodeContract3 = new DealercodeContract();
                        dealercodeContract3.setDealerNameCN(applac.getDealername());
                        dealercodeContract3.setSector(applac.getSector());
                        dealercodeContract3.setInstanceId(instanceId);
                        dealercodeContract3.setContractName("人民币循环贷款合同附件五");
                        dealercodeContract3.setLimitType(bc.getLimittype());
                        dealercodeContract3.setPriority(bc.getPriority());
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination ){
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String f =  contracthistory +"-5"+"-1";
                            //调用方法拼出主合同号
                            dealercodeContract3.setContract(f);
                            dealerSectorContractgroupadd.setContractname("人民币循环贷款合同附件五");
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                            }
                        }else {
                            String f =  contractNoMain +"-5"+"-1";
                            dealercodeContract3.setContract(f);
                            dealerSectorContractgroupadd.setContractname("人民币循环贷款合同附件五");
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                            }
                        }
                        dealercodeContractService.insertDealercodeContract(dealercodeContract3);
                        annualReviewyService.saveDbLog("1","新增合同信息",null,instanceId,null,dealercodeContract3,"CRO确认");
                    }
                    if (bc.getContractname().equals("浮动抵押")) {
                        //以主合同为准，字母后面的数据应与主合同F后的信息相同

                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination ){
                            //得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = dealercodelist+"M"+substring;
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                            }
                        }else {
                            StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                            String f = contractNoMainBuilder.replace(6,7,String.valueOf("M")).toString();
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                            }
                        }
                    }
                    if (bc.getContractname().equals("三方合同") || bc.getContractname().equals("三方-C") || bc.getContractname().equals("三方-E")) {
                        //以主合同为准，字母后面的数据应与主合同F后的信息相同

                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination  ){
                            //得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = dealercodelist+"W"+substring;
                            dealercodeContract.setContract(f);
                            if(bc.getContractname().equals("三方合同")){
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                                }
                            }
                        }else {
                            StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                            String f = contractNoMainBuilder.replace(6,7,String.valueOf("W")).toString();
                            dealercodeContract.setContract(f);
                            if(bc.getContractname().equals("三方合同")){
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                                }
                            }
                        }
                    }
                    if (bc.getContractname().equals("主信托")) {
                        //以主合同为准，字母后面的数据应与主合同F后的信息相同

                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination ){
                            //得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = dealercodelist+"T"+substring;
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                            }
                        }else {
                            StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                            String f = contractNoMainBuilder.replace(6,7,String.valueOf("T")).toString();
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                            }
                        }
                    }
                    if (bc.getContractname().equals("个人保函")) {
                        //此合同不同的业务场景，出来的合同也不一样，顾需区分
                        //当他为New application业务场景，走这个逻辑
                        if(bc.getPriority().equals("4")) {
                            //以主合同为准，字母后面的数据应与主合同F后的信息相同

                            //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                            if (StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination ) {
                                //得到历史合同编号，然后进行+1，用新编号进行拼接
                                String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                                String substring = contracthistory.substring(7,contracthistory.length());
                                //调用方法拼出主合同号
                                String f = dealercodelist+"G"+substring;
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                                }
                            } else {
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String f = contractNoMainBuilder.replace(6,7,String.valueOf("G")).toString();
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                                }
                            }
                        }
                        //当他为Change guarantee conditions场景走这个逻辑
                        if(bc.getPriority().equals("3") || bc.getPriority().equals("10")){
                            //以主合同为准，字母后面的数据应与主合同F后的信息相同
                            //查出来的同一个dealercode下的数据里的最大序列号值
//                            String SerialNumber = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroupTwo);
                            String count = null;
                            if(StringUtils.isEmpty(dealerSectorContractgroupsTwo)){
                                count = "2";
                            }else {
                                String contractnumber = dealerSectorContractgroupsTwo.get(0).getContractnumber();
                                int i = contractnumber.lastIndexOf("-");
                                String substring = contractnumber.substring(i + 1);
                                int i1 = Integer.parseInt(substring)+1;
                                count = String.valueOf(Double.valueOf(SerialNumberNormal).intValue());
                            }
                            //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                            if (StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination  ) {
                                //得到历史合同编号，然后进行+1，用新编号进行拼接
                                String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                                String substring = contracthistory.substring(7,contracthistory.length());
                                //调用方法拼出主合同号
                                String f = null;
                                if(StringUtils.isEmpty(count)){
                                    f = dealercodelist+"G"+substring;
                                }else{
                                    f = dealercodelist+"G"+substring+"-"+count;
                                }
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                                }
                            } else {
                                if(isTermination){
                                    count = "2";
                                }
                                String f = null;
                                if(StringUtils.isEmpty(count)){
                                    StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                    f = contractNoMainBuilder.replace(6,7,String.valueOf("G")).toString();
                                }else{
                                    StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                    String g = contractNoMainBuilder.replace(6, 7, String.valueOf("G")).toString();
                                    f = g +"-"+ count;
                                }
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                                }
                            }
                        }
                    }
                    if (bc.getContractname().equals("企业保函")) {
                        //以主合同为准，字母后面的数据应与主合同F后的信息相同
                        if(bc.getPriority().equals("4")) {
                            //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                            if (StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination   ) {
                                //得到历史合同编号，然后进行+1，用新编号进行拼接
                                String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                                String substring = contracthistory.substring(7,contracthistory.length());
                                //调用方法拼出主合同号
                                String f = dealercodelist+"C"+substring;
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                                }
                            } else {
                                //既然历史合同号不存在，新经销商合同编号肯定要从001开始算
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String f = contractNoMainBuilder.replace(6,7,String.valueOf("C")).toString();;
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                                }
                            }
                        }
                        //当他为Change guarantee conditions场景走这个逻辑
                        if(bc.getPriority().equals("3") || bc.getPriority().equals("10")){
                            //以主合同为准，字母后面的数据应与主合同F后的信息相同
                            //查出来的同一个dealercode下的数据里的最大序列号值
//                            String SerialNumber = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroupTwo);
                            String count = null;
                            if(StringUtils.isEmpty(dealerSectorContractgroupsTwo)){
                                count = "2";
                            }else {
                                String contractnumber = dealerSectorContractgroupsTwo.get(0).getContractnumber();
                                int i = contractnumber.lastIndexOf("-");
                                String substring = contractnumber.substring(i + 1);
                                int i1 = Integer.parseInt(substring)+1;
                                count = String.valueOf(Double.valueOf(SerialNumberNormal).intValue());
                            }
                            //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                            if (StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination  ) {
                                //得到历史合同编号，然后进行+1，用新编号进行拼接
                                String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                                String substring = contracthistory.substring(7,contracthistory.length());
                                //调用方法拼出主合同号
                                String f = null;
                                if(StringUtils.isEmpty(count)){
                                    f = dealercodelist+"C"+substring;
                                }else{
                                    f = dealercodelist+"C"+substring+"-"+count;
                                }
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                                }
                            } else {
                                if(isTermination){
                                    count = "2";
                                }
                                String f = null;
                                if(StringUtils.isEmpty(count)){
                                    StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                    f = contractNoMainBuilder.replace(6,7,String.valueOf("C")).toString();
                                }else{
                                    StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                    String g = contractNoMainBuilder.replace(6, 7, String.valueOf("C")).toString();
                                    f = g +"-"+ count;
                                }
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                                }
                            }
                        }
                    }
                    if (bc.getContractname().equals("人民币循环贷款协议补充协议-二网服务费")) {
                        //以主合同为准，字母后面的数据应与主合同F后的信息相同
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination ){
                            //得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = dealercodelist+"F"+substring;
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                            }
                        }else {
                            dealercodeContract.setContract(contractNoMain);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(contractNoMain);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                            }
                        }
                    }
                    if (bc.getContractname().equals("试乘试驾车贷款合同")) {
                        //以主合同为准，字母后面的数据应与主合同F后的信息相同
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination ){
                            //得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = dealercodelist+"DEMO"+substring;
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                            }
                        }else {
                            StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                            String f = contractNoMainBuilder.replace(6,7,String.valueOf("DEMO")).toString();
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                            }
                        }

                        //主合同内容里包含了附件合同号，所以附件也要生成
                        DealercodeContract dealercodeContract1 = new DealercodeContract();
                        dealercodeContract1.setDealerNameCN(applac.getDealername());
                        dealercodeContract1.setSector(applac.getSector());
                        dealercodeContract1.setInstanceId(instanceId);
                        dealercodeContract1.setContractName("试乘试驾车贷款合同附件一");
                        dealercodeContract1.setLimitType(bc.getLimittype());
                        dealercodeContract1.setPriority(bc.getPriority());
                        dealerSectorContractgroup.setContractname("试乘试驾车贷款合同附件一");
                        List<DealerSectorContractgroup> dealerSectorContractgroupsAccessory = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                        //查出来的同一个dealercode下的数据里的最大序列号值
//                        String SerialNumber = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroup);
                        String count = null;
                        if(StringUtils.isEmpty(dealerSectorContractgroupsAccessory) && StringUtils.isEmpty(dealerSectorContractgroupsDemo)){
                            count = "1";
                        }else if(StringUtils.isEmpty(dealerSectorContractgroupsAccessory) && StringUtils.isNotEmpty(dealerSectorContractgroupsDemo)){
                            count = "2";
                        }else {
                            String contractnumber = dealerSectorContractgroupsAccessory.get(0).getContractnumber();
                            int i = contractnumber.lastIndexOf("-");
                            String substring = contractnumber.substring(i + 1);
                            int i1 = Integer.parseInt(substring)+1;
                            count = String.valueOf(Double.valueOf(SerialNumberDemo).intValue());
                        }
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination ){
                            //得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f = dealercodelist+"DEMO"+substring+"-1";
                            }else{
                                f = dealercodelist+"DEMO"+substring+"-1"+"-"+count;
                            }
                            dealercodeContract1.setContract(f);
                            dealerSectorContractgroupadd.setContractname("试乘试驾车贷款合同附件一");
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                        }else {
                            if(isTermination){
                                count = "1";
                            }
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g =contractNoMainBuilder.replace(6,7,String.valueOf("DEMO")).toString();
                                f = g +"-1";
                            }else{
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g = contractNoMainBuilder.replace(6, 7, String.valueOf("DEMO")).toString();
                                f = g +"-1"+"-"+count;
                            }
                            dealercodeContract1.setContract(f);
                            dealerSectorContractgroupadd.setContractname("试乘试驾车贷款合同附件一");
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                        }
                        dealercodeContractService.insertDealercodeContract(dealercodeContract1);
                        annualReviewyService.saveDbLog("1","新增合同信息",null,instanceId,null,dealercodeContract1,"CRO确认");

                        DealercodeContract dealercodeContract2 = new DealercodeContract();
                        dealercodeContract2.setDealerNameCN(applac.getDealername());
                        dealercodeContract2.setSector(applac.getSector());
                        dealercodeContract2.setInstanceId(instanceId);
                        dealercodeContract2.setContractName("试乘试驾车贷款合同附件二");
                        dealercodeContract2.setLimitType(bc.getLimittype());
                        dealercodeContract2.setPriority(bc.getPriority());
                        if (StringUtils.isEmpty(dealerSectorContractgroupsDemoOne) && StringUtils.isEmpty(dealerSectorContractgroupsDemo)) {
                            count = "1";
                        } else if(StringUtils.isEmpty(dealerSectorContractgroupsDemoOne) && StringUtils.isNotEmpty(dealerSectorContractgroupsDemo)){
                            count = "2";
                        } else {
                            count = String.valueOf(Double.valueOf(SerialNumberDemo).intValue());
                        }
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination){
                            //得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f = dealercodelist+"DEMO"+substring+"-2";
                            }else{
                                f = dealercodelist+"DEMO"+substring+"-2"+"-"+count;
                            }
                            dealercodeContract2.setContract(f);
                            dealerSectorContractgroupadd.setContractname("试乘试驾车贷款合同附件二");
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                        }else {
                            if(isTermination){
                                count = "1";
                            }
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g =contractNoMainBuilder.replace(6,7,String.valueOf("DEMO")).toString();
                                f = g +"-2";
                            }else{
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g = contractNoMainBuilder.replace(6, 7, String.valueOf("DEMO")).toString();
                                f = g +"-2"+"-"+count;
                            }
                            dealercodeContract2.setContract(f);
                            dealerSectorContractgroupadd.setContractname("试乘试驾车贷款合同附件二");
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                        }
                        dealercodeContractService.insertDealercodeContract(dealercodeContract2);
                        annualReviewyService.saveDbLog("1","新增合同信息",null,instanceId,null,dealercodeContract2,"CRO确认");

                        if(applac.getSector().toUpperCase().equals("ALFA ROMEO")|| applac.getSector().toUpperCase().equals("DS") || applac.getSector().toUpperCase().equals("CHRYSLER")){
                            DealercodeContract dealerCodeContract3 = new DealercodeContract();
                            dealerCodeContract3.setDealerNameCN(applac.getDealername());
                            dealerCodeContract3.setSector(applac.getSector());
                            dealerCodeContract3.setInstanceId(instanceId);
                            dealerCodeContract3.setContractName("试乘试驾车贷款合同附件三");
                            dealerCodeContract3.setLimitType(bc.getLimittype());
                            dealerCodeContract3.setPriority(bc.getPriority());
                            //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination){
                                //得到历史合同编号，然后进行+1，用新编号进行拼接
                                String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                                String substring = contracthistory.substring(7,contracthistory.length());
                                //调用方法拼出主合同号
                                String f = null;
                                f = dealercodelist+"DEMO"+substring+"-3"+"-1";
                                dealerCodeContract3.setContract(f);
                                dealerSectorContractgroupadd.setContractname("试乘试驾车贷款合同附件三");
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                            }else {
                                String f = null;
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g = contractNoMainBuilder.replace(6, 7, String.valueOf("DEMO")).toString();
                                f = g +"-3"+"-1";
                                dealerCodeContract3.setContract(f);
                                dealerSectorContractgroupadd.setContractname("试乘试驾车贷款合同附件三");
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                            }
                            dealercodeContractService.insertDealercodeContract(dealerCodeContract3);
                            annualReviewyService.saveDbLog("1","新增合同信息",null,instanceId,null,dealercodeContract2,"CRO确认");
                        }
                    }
                    if (bc.getContractname().equals("试驾车个人保函")) {
                        //此合同不同的业务场景，出来的合同也不一样，顾需区分
                        //当他为New application业务场景，走这个逻辑
                        if(bc.getPriority().equals("4")) {
                            //以主合同为准，字母后面的数据应与主合同F后的信息相同

                            //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                            if (StringUtils.isNotEmpty(dealerSectorContractgroups) && !isTermination ) {
                                //得到历史合同编号，然后进行+1，用新编号进行拼接
                                String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                                String substring = contracthistory.substring(7,contracthistory.length());
                                //调用方法拼出主合同号
                                String f = dealercodelist+"DEMO"+substring+"-G";
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                                }
                            } else {
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g = contractNoMainBuilder.replace(6, 7, String.valueOf("DEMO")).toString();
                                String f = g +"-G";
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                                }
                            }
                        }
                        //当他为Change guarantee conditions场景走这个逻辑
                        if(bc.getPriority().equals("3")) {
                            //以主合同为准，字母后面的数据应与主合同F后的信息相同
                            //查出来的同一个dealercode下的数据里的最大序列号值
//                            String SerialNumber = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroupDemoOne);
                            String count = null;
                            if (StringUtils.isEmpty(dealerSectorContractgroupsDemoOne)) {
                                count = "2";
                            } else {
                                String contractnumber = dealerSectorContractgroupsDemoOne.get(0).getContractnumber();
                                int i = contractnumber.lastIndexOf("-");
                                String substring = contractnumber.substring(i + 1);
                                int i1 = Integer.parseInt(substring) + 1;
                                count = String.valueOf(Double.valueOf(SerialNumberDemo).intValue());
                            }
                            //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                            if (StringUtils.isNotEmpty(dealerSectorContractgroups) && !isTermination) {
                                //得到历史合同编号，然后进行+1，用新编号进行拼接
                                String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                                String substring = contracthistory.substring(7,contracthistory.length());
                                //调用方法拼出主合同号
                                String f = null;
                                if(StringUtils.isEmpty(count)){
                                    f = dealercodelist+"DEMO"+substring+"-G";
                                }else{
                                    f = dealercodelist+"DEMO"+substring+"-G"+"-"+count;
                                }
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                                }
                            } else {
                                if(isTermination){
                                    count = "2";
                                }
                                String f = null;
                                if(StringUtils.isEmpty(count)){
                                    StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                    String g =contractNoMainBuilder.replace(6,7,String.valueOf("DEMO")).toString();
                                    f = g +"-G";
                                }else{
                                    StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                    String g = contractNoMainBuilder.replace(6, 7, String.valueOf("DEMO")).toString();
                                    f = g +"-G"+"-"+count;
                                }
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                                }
                            }
                        }
                    }
                    if (bc.getContractname().equals("试驾车企业保函")) {
                        //此合同不同的业务场景，出来的合同也不一样，顾需区分
                        //当他为New application业务场景，走这个逻辑
                        if(bc.getPriority().equals("4")) {
                            //以主合同为准，字母后面的数据应与主合同F后的信息相同

                            //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                            if (StringUtils.isNotEmpty(dealerSectorContractgroups) && !isTermination) {
                                //得到历史合同编号，然后进行+1，用新编号进行拼接
                                String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                                String substring = contracthistory.substring(7,contracthistory.length());
                                //调用方法拼出主合同号
                                String f = dealercodelist+"DEMO"+substring+"-C";
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                                }
                            } else {
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g = contractNoMainBuilder.replace(6, 7, String.valueOf("DEMO")).toString();
                                String f = g +"-C";
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                                }
                            }
                        }
                        //当他为Change guarantee conditions场景走这个逻辑
                        if(bc.getPriority().equals("3")) {
                            //以主合同为准，字母后面的数据应与主合同F后的信息相同
                            //查出来的同一个dealercode下的数据里的最大序列号值
//                            String SerialNumber = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroupDemoOne);
                            String count = null;
                            if (StringUtils.isEmpty(dealerSectorContractgroupsDemoOne)) {
                                count = "2";
                            } else {
                                String contractnumber = dealerSectorContractgroupsDemoOne.get(0).getContractnumber();
                                int i = contractnumber.lastIndexOf("-");
                                String substring = contractnumber.substring(i + 1);
                                int i1 = Integer.parseInt(substring) + 1;
                                count = String.valueOf(Double.valueOf(SerialNumberDemo).intValue());
                            }
                            //以主合同为准，字母后面的数据应与主合同F后的信息相同

                            //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                            if (StringUtils.isNotEmpty(dealerSectorContractgroups) && !isTermination) {
                                //得到历史合同编号，然后进行+1，用新编号进行拼接
                                String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                                String substring = contracthistory.substring(7,contracthistory.length());
                                //调用方法拼出主合同号
                                String f = null;
                                if(StringUtils.isEmpty(count)){
                                    f = dealercodelist+"DEMO"+substring+"-C";
                                }else{
                                    f = dealercodelist+"DEMO"+substring+"-C"+"-"+count;
                                }
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                                }
                            } else {
                                if(isTermination){
                                    count = "2";
                                }
                                String f = null;
                                if(StringUtils.isEmpty(count)){
                                    StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                    String g =contractNoMainBuilder.replace(6,7,String.valueOf("DEMO")).toString();
                                    f = g +"-C";
                                }else{
                                    StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                    String g = contractNoMainBuilder.replace(6, 7, String.valueOf("DEMO")).toString();
                                    f = g +"-C"+"-"+count;
                                }
                                dealercodeContract.setContract(f);
                                dealerSectorContractgroupadd.setContractname(bc.getContractname());
                                List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                                dealerSectorContractgroupadd.setContractnumber(f);
                                dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                                //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                                if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                    dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                                }else {
                                    dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                    annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                                }
                            }
                        }
                    }


                    if (bc.getContractname().equals("人民币循环贷款合同附件二")) {
                        //合同附件编号前十几位应该跟主合同F对齐
                        //查历史合同附件，取编号以便进行递增
                        dealerSectorContractgroup.setContractname("人民币循环贷款合同附件二");
                        List<DealerSectorContractgroup> dealerSectorContractgroupsAccessory = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                        //查出来的同一个dealercode下的数据里的最大序列号值
//                        String SerialNumber = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroup);
                        String count = null;
                        if(StringUtils.isEmpty(dealerSectorContractgroupsAccessory)){
                            count = "2";
                        }else {
                            String contractnumber = dealerSectorContractgroupsAccessory.get(0).getContractnumber();
                            int i = contractnumber.lastIndexOf("-");
                            String substring = contractnumber.substring(i + 1);
                            int i1 = Integer.parseInt(substring)+1;
                            count = String.valueOf(Double.valueOf(SerialNumberNormal).intValue());
                        }
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups) && !isTermination){
                            //得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f = dealercodelist+"F"+substring+"-2";
                            }else{
                                f = dealercodelist+"F"+substring+"-2"+"-"+count;
                            }
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }else {
                            if(isTermination){
                                count = "1";
                            }
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f = contractNoMain +"-2";
                            }else{
                                f = contractNoMain +"-2"+"-"+count;
                            }
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }
                    }
                    if (bc.getContractname().equals("人民币循环贷款合同附件三")) {
                        //以主合同为准，字母后面的数据应与主合同F后的信息相同

                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination){
                            //得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = dealercodelist+"F"+substring;
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                            }
                        }else {
                            dealercodeContract.setContract(contractNoMain);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(contractNoMain);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                            }
                        }
                    }
                    if (bc.getContractname().equals("人民币循环贷款合同附件四")) {
                        //合同附件编号前十几位应该跟主合同F对齐
                        //查历史合同附件，取编号以便进行递增
//                        dealerSectorContractgroup.setContractname("人民币循环贷款合同附件四");
//                        List<DealerSectorContractgroup> dealerSectorContractgroupsAccessory = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                        //查出来的同一个dealercode下的数据里的最大序列号值
                        //附件四序列号应该跟附件二保持一致
//                        String SerialNumber = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroupTwo);
                        String count = null;
                        if(StringUtils.isEmpty(dealerSectorContractgroupsTwo)){
                            count = "2";
                        }else {
                            String contractnumber = dealerSectorContractgroupsTwo.get(0).getContractnumber();
                            int i = contractnumber.lastIndexOf("-");
                            String substring = contractnumber.substring(i + 1);
                            int i1 = Integer.parseInt(substring)+1;
                            count = String.valueOf(Double.valueOf(SerialNumberNormal).intValue());
                        }
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination ){
                            //得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f = dealercodelist+"F"+substring+"-4";
                            }else{
                                f = dealercodelist+"F"+substring+"-4"+"-"+count;
                            }
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }else {
                            if(isTermination){
                                count = "1";
                            }
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f = contractNoMain +"-4";
                            }else{
                                f = contractNoMain +"-4"+"-"+count;
                            }
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }
                    }
                    if (bc.getContractname().equals("人民币循环贷款合同附件五")) {
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups) && !isTermination){
                            //得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = dealercodelist+"F"+substring+"-5"+"-1";
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                            }
                        }else {
                            String f = contractNoMain +"-5-1";
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                            }
                        }
                    }
                    if (bc.getContractname().equals("试乘试驾车贷款合同附件一")) {
                        //合同附件编号前十几位应该跟主合同F对齐
                        //查历史合同附件，取编号以便进行递增
                        dealerSectorContractgroup.setContractname("试乘试驾车贷款合同附件一");
                        List<DealerSectorContractgroup> dealerSectorContractgroupsAccessory = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                        //查出来的同一个dealercode下的数据里的最大序列号值
//                        String SerialNumber = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroup);
                        String count = null;
                        if(StringUtils.isEmpty(dealerSectorContractgroupsAccessory)){
                            count = "2";
                        }else {
                            String contractnumber = dealerSectorContractgroupsAccessory.get(0).getContractnumber();
                            int i = contractnumber.lastIndexOf("-");
                            String substring = contractnumber.substring(i + 1);
                            int i1 = Integer.parseInt(substring)+1;
                            count = String.valueOf(Double.valueOf(SerialNumberDemo).intValue());
                        }
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups) && !isTermination ){
                            ///得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f = dealercodelist+"DEMO"+substring+"-1";
                            }else{
                                f = dealercodelist+"DEMO"+substring+"-1"+"-"+count;
                            }
                            //调用方法拼出主合同号
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }else {
                            if(isTermination){
                                count = "1";
                            }
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g =contractNoMainBuilder.replace(6,7,String.valueOf("DEMO")).toString();
                                f = g +"-1";
                            }else{
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g = contractNoMainBuilder.replace(6, 7, String.valueOf("DEMO")).toString();
                                f = g +"-1"+"-"+count;
                            }
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }
                    }
                    if (bc.getContractname().equals("试乘试驾车贷款合同附件二")) {
                        //合同附件编号前十几位应该跟主合同F对齐
                        //查历史合同附件，取编号以便进行递增
//                        dealerSectorContractgroup.setContractname("试乘试驾车贷款合同附件二");
//                        List<DealerSectorContractgroup> dealerSectorContractgroupsAccessory = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                        //查出来的同一个dealercode下的数据里的最大序列号值
                        //附件二序列号要与附件一序列号保持一致
//                        String SerialNumber = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroupDemoOne);
                        String count = null;
                        if (StringUtils.isEmpty(dealerSectorContractgroupsDemoOne)) {
                            count = "2";
                        } else {
                            String contractnumber = dealerSectorContractgroupsDemoOne.get(0).getContractnumber();
                            int i = contractnumber.lastIndexOf("-");
                            String substring = contractnumber.substring(i + 1);
                            int i1 = Integer.parseInt(substring) + 1;
                            count = String.valueOf(Double.valueOf(SerialNumberDemo).intValue());
                        }
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups) && !isTermination ){
                            ///得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f = dealercodelist+"DEMO"+substring+"-2";
                            }else{
                                f = dealercodelist+"DEMO"+substring+"-2"+"-"+count;
                            }
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }else {
                            if(isTermination){
                                count = "1";
                            }
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g =contractNoMainBuilder.replace(6,7,String.valueOf("DEMO")).toString();
                                f = g +"-2";
                            }else{
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g = contractNoMainBuilder.replace(6, 7, String.valueOf("DEMO")).toString();
                                f = g +"-2"+"-"+count;
                            }
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }
                    }
                    if (bc.getContractname().equals("试乘试驾车贷款合同附件三")) {
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups) && !isTermination ){
                            ///得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = null;
                            f = dealercodelist+"DEMO"+substring+"-3-1";
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                        }else {
                            StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                            String g = contractNoMainBuilder.replace(6, 7, String.valueOf("DEMO")).toString();
                            String f = g +"-3-1";
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                        }
                    }

                    if (bc.getContractname().equals("CB 改装车协议（循环）")) {
                        //以主合同为准，字母后面的数据应与主合同F后的信息相同

                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups) && !isTermination){
                            //得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = dealercodelist+"CB"+substring;
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                            }
                        }else {
                            StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                            String f = contractNoMainBuilder.replace(6, 7, String.valueOf("CB")).toString();
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                            }
                        }

                        //主合同内容里包含了附件合同号，所以附件也要生成
                        DealercodeContract dealercodeContract1 = new DealercodeContract();
                        dealercodeContract1.setDealerNameCN(applac.getDealername());
                        dealercodeContract1.setSector(applac.getSector());
                        dealercodeContract1.setInstanceId(instanceId);
                        dealercodeContract1.setContractName("CB 改装车延期还款产品条款附件（循环）");
                        dealercodeContract1.setLimitType(bc.getLimittype());
                        dealercodeContract1.setPriority(bc.getPriority());
                        dealerSectorContractgroup.setContractname("CB 改装车延期还款产品条款附件（循环）");
                        List<DealerSectorContractgroup> dealerSectorContractgroupsAccessory = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                        //查出来的同一个dealercode下的数据里的最大序列号值
                        String SerialNumber = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroup);
                        String count = null;
                        if(StringUtils.isEmpty(dealerSectorContractgroupsAccessory) && StringUtils.isEmpty(dealerSectorContractgroupsCbRevolving)){
                            count = "1";
                        }else if(StringUtils.isEmpty(dealerSectorContractgroupsAccessory) && StringUtils.isNotEmpty(dealerSectorContractgroupsCbRevolving)){
                            count = "2";
                        }else {
                            count = String.valueOf(Double.valueOf(SerialNumber).intValue());
                        }
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination){
                            ///得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f = dealercodelist+"CB"+substring+"-1";
                            }else{
                                f = dealercodelist+"CB"+substring+"-1"+"-"+count;
                            }
                            dealercodeContract1.setContract(f);
                            dealerSectorContractgroupadd.setContractname("CB 改装车延期还款产品条款附件（循环）");
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                        }else {
                            if(isTermination){
                                count = "1";
                            }
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g =contractNoMainBuilder.replace(6,7,String.valueOf("CB")).toString();
                                f = g +"-1";
                            }else{
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g = contractNoMainBuilder.replace(6, 7, String.valueOf("CB")).toString();
                                f = g +"-1"+"-"+count;
                            }
                            dealercodeContract1.setContract(f);
                            dealerSectorContractgroupadd.setContractname("CB 改装车延期还款产品条款附件（循环）");
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                        }
                        dealercodeContractService.insertDealercodeContract(dealercodeContract1);
                        annualReviewyService.saveDbLog("1","新增合同信息",null,instanceId,null,dealercodeContract1,"CRO确认");
                    }
                    if (bc.getContractname().equals("CB 改装车延期还款产品条款附件（循环）")) {
                        //合同附件编号前十几位应该跟主合同F对齐
                        //查历史合同附件，取编号以便进行递增
                        dealerSectorContractgroup.setContractname("CB 改装车延期还款产品条款附件（循环）");
                        List<DealerSectorContractgroup> dealerSectorContractgroupsAccessory = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                        //查出来的同一个dealercode下的数据里的最大序列号值
                        String SerialNumber = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroup);
                        String count = null;
                        if(StringUtils.isEmpty(dealerSectorContractgroupsAccessory)){
                            count = "2";
                        }else {
                            String contractnumber = dealerSectorContractgroupsAccessory.get(0).getContractnumber();
                            int i = contractnumber.lastIndexOf("-");
                            String substring = contractnumber.substring(i + 1);
                            int i1 = Integer.parseInt(substring)+1;
                            count = String.valueOf(Double.valueOf(SerialNumber).intValue());
                        }
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)   && !isTermination ){
                            ///得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f = dealercodelist+"CB"+substring+"-1";
                            }else{
                                f = dealercodelist+"CB"+substring+"-1"+"-"+count;
                            }
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }else {
                            if(isTermination){
                                count = "1";
                            }
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g =contractNoMainBuilder.replace(6,7,String.valueOf("CB")).toString();
                                f = g +"-1";
                            }else{
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g = contractNoMainBuilder.replace(6, 7, String.valueOf("CB")).toString();
                                f = g +"-1"+"-"+count;
                            }
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }
                    }
                    if (bc.getContractname().equals("CB 大客户协议（一次性额度）")) {
                        //以主合同为准，字母后面的数据应与主合同F后的信息相同

                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination ){
                            //得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = dealercodelist+"CB"+substring;
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                            }
                        }else {
                            StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                            String f =contractNoMainBuilder.replace(6,7,String.valueOf("CB")).toString();
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //当这个合同在历史合同数据里存在，就修改，不存在，就新增
                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
                            }else {
                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                                annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");
                            }
                        }

                        //主合同内容里包含了附件合同号，所以附件也要生成
                        DealercodeContract dealercodeContract1 = new DealercodeContract();
                        dealercodeContract1.setDealerNameCN(applac.getDealername());
                        dealercodeContract1.setSector(applac.getSector());
                        dealercodeContract1.setInstanceId(instanceId);
                        dealercodeContract1.setContractName("CB 大客户延期还款产品担保附件一");
                        dealercodeContract1.setLimitType(bc.getLimittype());
                        dealercodeContract1.setPriority(bc.getPriority());
                        dealerSectorContractgroup.setContractname("CB 大客户延期还款产品担保附件一");
                        List<DealerSectorContractgroup> dealerSectorContractgroupsAccessory = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                        //查出来的同一个dealercode下的数据里的最大序列号值
                        String SerialNumber = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroup);
                        String count = null;
                        if(StringUtils.isEmpty(dealerSectorContractgroupsAccessory) && StringUtils.isEmpty(dealerSectorContractgroupsCboneoffFleet)){
                            count = "1";
                        }else if(StringUtils.isEmpty(dealerSectorContractgroupsAccessory) && StringUtils.isNotEmpty(dealerSectorContractgroupsCboneoffFleet)){
                            count = "2";
                        }else {
                            count = String.valueOf(Double.valueOf(SerialNumberCB).intValue());
                        }
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination ){
                            ///得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f = dealercodelist+"CB"+substring+"-1";
                            }else{
                                f = dealercodelist+"CB"+substring+"-1"+"-"+count;
                            }
                            dealercodeContract1.setContract(f);
                            dealerSectorContractgroupadd.setContractname("CB 大客户延期还款产品担保附件一");
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                        }else {
                            if(isTermination){
                                count = "1";
                            }
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g =contractNoMainBuilder.replace(6,7,String.valueOf("CB")).toString();
                                f = g +"-1";
                            }else{
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g = contractNoMainBuilder.replace(6, 7, String.valueOf("CB")).toString();
                                f = g +"-1"+"-"+count;
                            }
                            dealercodeContract1.setContract(f);
                            dealerSectorContractgroupadd.setContractname("CB 大客户延期还款产品担保附件一");
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                        }
                        dealercodeContractService.insertDealercodeContract(dealercodeContract1);
                        annualReviewyService.saveDbLog("1","新增合同信息",null,instanceId,null,dealercodeContract1,"CRO确认");

                        DealercodeContract dealercodeContract2 = new DealercodeContract();
                        dealercodeContract2.setDealerNameCN(applac.getDealername());
                        dealercodeContract2.setSector(applac.getSector());
                        dealercodeContract2.setInstanceId(instanceId);
                        dealercodeContract2.setContractName("CB 大客户延期还款产品担保附件二");
                        dealercodeContract2.setLimitType(bc.getLimittype());
                        dealercodeContract2.setPriority(bc.getPriority());
                        dealerSectorContractgroup.setContractname("CB 大客户延期还款产品担保附件二");
                        List<DealerSectorContractgroup> dealerSectorContractgroupsAccessoryTwo = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                        //查出来的同一个dealercode下的数据里的最大序列号值
                        String SerialNumberTwo = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroup);
                        if(StringUtils.isEmpty(dealerSectorContractgroupsCBOne) && StringUtils.isEmpty(dealerSectorContractgroupsCboneoffFleet)){
                            count = "1";
                        }else if(StringUtils.isEmpty(dealerSectorContractgroupsCBOne) && StringUtils.isNotEmpty(dealerSectorContractgroupsCboneoffFleet)){
                            count = "2";
                        }else {
                            count = String.valueOf(Double.valueOf(SerialNumberCB).intValue());
                        }
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups) && !isTermination ){
                            ///得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f = dealercodelist+"CB"+substring+"-2";
                            }else{
                                f = dealercodelist+"CB"+substring+"-2"+"-"+count;
                            }
                            dealercodeContract2.setContract(f);
                            dealerSectorContractgroupadd.setContractname("CB 大客户延期还款产品担保附件二");
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                        }else {
                            if(isTermination){
                                count = "1";
                            }
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g =contractNoMainBuilder.replace(6,7,String.valueOf("CB")).toString();
                                f = g +"-2";
                            }else{
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g = contractNoMainBuilder.replace(6, 7, String.valueOf("CB")).toString();
                                f = g +"-2"+"-"+count;
                            }
                            dealercodeContract2.setContract(f);
                            dealerSectorContractgroupadd.setContractname("CB 大客户延期还款产品担保附件二");
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

                        }
                        dealercodeContractService.insertDealercodeContract(dealercodeContract2);
                        annualReviewyService.saveDbLog("1","新增合同信息",null,instanceId,null,dealercodeContract2,"CRO确认");
                    }
                    if (bc.getContractname().equals("CB 大客户延期还款产品担保附件一")) {
                        //合同附件编号前十几位应该跟主合同F对齐
                        //查历史合同附件，取编号以便进行递增
                        dealerSectorContractgroup.setContractname("CB 大客户延期还款产品担保附件一");
                        List<DealerSectorContractgroup> dealerSectorContractgroupsAccessory = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                        //查出来的同一个dealercode下的数据里的最大序列号值
                        String SerialNumber = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroup);
                        String count = null;
                        if(StringUtils.isEmpty(dealerSectorContractgroupsAccessory)){
                            count = "2";
                        }else {
//                            String contractnumber = dealerSectorContractgroupsAccessory.get(0).getContractnumber();
//                            int i = contractnumber.lastIndexOf("-");
//                            String substring = contractnumber.substring(i + 1);
//                            int i1 = Integer.parseInt(substring)+1;
                            count = String.valueOf(Double.valueOf(SerialNumberCB).intValue());
                        }
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)&& !isTermination){
                            ///得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f = dealercodelist+"CB"+substring+"-1";
                            }else{
                                f = dealercodelist+"CB"+substring+"-1"+"-"+count;
                            }
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }else {
                            if(isTermination){
                                count = "1";
                            }
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g =contractNoMainBuilder.replace(6,7,String.valueOf("CB")).toString();
                                f = g +"-1";
                            }else{
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g = contractNoMainBuilder.replace(6, 7, String.valueOf("CB")).toString();
                                f = g +"-1"+"-"+count;
                            }
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }
                    }
                    if (bc.getContractname().equals("CB 大客户延期还款产品担保附件二")) {
                        //合同附件编号前十几位应该跟主合同F对齐
                        //查历史合同附件，取编号以便进行递增
                        dealerSectorContractgroup.setContractname("CB 大客户延期还款产品担保附件一");
//                        List<DealerSectorContractgroup> dealerSectorContractgroupsAccessory = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                        //查出来的同一个dealercode下的数据里的最大序列号值
                        String SerialNumber = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroup);
                        String count = null;
                        if(StringUtils.isEmpty(dealerSectorContractgroupsCBOne)){
                            count = "2";
                        }else {
//                            String contractnumber = dealerSectorContractgroupsAccessory.get(0).getContractnumber();
//                            int i = contractnumber.lastIndexOf("-");
//                            String substring = contractnumber.substring(i + 1);
//                            int i1 = Integer.parseInt(substring)+1;
                            count = String.valueOf(Double.valueOf(SerialNumberCB).intValue());
                        }
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups) && !isTermination ){
                            ///得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f = dealercodelist+"CB"+substring+"-2";
                            }else{
                                f = dealercodelist+"CB"+substring+"-2"+"-"+count;
                            }
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }else {
                            if(isTermination){
                                count = "1";
                            }
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g =contractNoMainBuilder.replace(6,7,String.valueOf("CB")).toString();
                                f = g +"-2";
                            }else{
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g = contractNoMainBuilder.replace(6, 7, String.valueOf("CB")).toString();
                                f = g +"-2"+"-"+count;
                            }
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }
                    }

                    if (bc.getContractname().equals("CB 改装车大客户延期补充协议")) {
                        //合同附件编号前十几位应该跟主合同F对齐
                        //查历史合同附件，取编号以便进行递增
                        dealerSectorContractgroup.setContractname("CB 大客户延期还款产品担保附件一");
//                        List<DealerSectorContractgroup> dealerSectorContractgroupsAccessory = dealerSectorContractgroupService.selectDealerSectorContractgroupList(dealerSectorContractgroup);
                        //查出来的同一个dealercode下的数据里的最大序列号值
                        String SerialNumber = dealerSectorContractgroupMapper.selectMaxSerialNumber(dealerSectorContractgroup);
                        String count = null;
                        if(StringUtils.isNotEmpty(dealerSectorContractgroupsCBnew)){
                            if(dealerSectorContractgroupsCBnew.size()==1 && dealerSectorContractgroupsCBnew.get(0).getContractnumber().length() == 16){
                                count = "2";
                            }else {
                                count = String.valueOf(Double.valueOf(SerialNumberCBnew).intValue());
                            }
                        }
                        //此处判断就是当他在历史合同表里有数据的时候就取历史合同号做处理，如果没有就拼新合同号
                        if(StringUtils.isNotEmpty(dealerSectorContractgroups)  && !isTermination ){
                            ///得到历史合同编号，然后进行+1，用新编号进行拼接
                            String contracthistory = dealerSectorContractgroups.get(0).getContractnumber();
                            String substring = contracthistory.substring(7,contracthistory.length());
                            //调用方法拼出主合同号
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                f = dealercodelist+"CB"+substring;
                            }else{
                                f = dealercodelist+"CB"+substring+"-"+count;
                            }
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }else {
                            if(isTermination){
                                count = "";
                            }
                            String f = null;
                            if(StringUtils.isEmpty(count)){
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g =contractNoMainBuilder.replace(6,7,String.valueOf("CB")).toString();
                                f = g;
                            }else{
                                StringBuilder contractNoMainBuilder = new StringBuilder(contractNoMain);
                                String g = contractNoMainBuilder.replace(6, 7, String.valueOf("CB")).toString();
                                f = g +"-"+ count;
                            }
                            dealercodeContract.setContract(f);
                            dealerSectorContractgroupadd.setContractname(bc.getContractname());
                            List<DealerSectorContractgroup> dealerSectorContractgroups1 = dealerSectorContractgroupMapper.selectDealerSectorContractgroupList(dealerSectorContractgroupadd);
                            dealerSectorContractgroupadd.setContractnumber(f);
                            dealerSectorContractgroupadd.setExpDate(DateUtils.getDate());
                            //附件这些合同，在历史合同数据里是多个存在的，只是序列号不同，所以，不管这个附件合同号存不存在都要新增
                            dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
                            annualReviewyService.saveDbLog("1","新增合同历史",null,instanceId,null,dealerSectorContractgroupadd,"CRO确认");

//                            if(StringUtils.isNotEmpty(dealerSectorContractgroups1)){
//                                dealerSectorContractgroupMapper.updateDealerSectorContractgroupWhere(dealerSectorContractgroupadd);
//                            }else {
//                                dealerSectorContractgroupMapper.insertDealerSectorContractgroup(dealerSectorContractgroupadd);
//                            }
                        }
                    }


//                if(bc.getContractname().equals("集团经销商保证金共享协议")){
//                    //调用方法拼出主合同号
//                    dealerInformationMapper.selectDealerInformationByname()
//                    String f = ;
//                    dealercodeContract.setContract(f+"-M");
//                }
                    dealercodeContractService.insertDealercodeContract(dealercodeContract);
                    annualReviewyService.saveDbLog("1","新增合同信息",null,instanceId,null,dealercodeContract,"CRO确认");
                    ContractRecord contractRecord = new ContractRecord();
                    contractRecord.setSector(bc.getSector());
                    contractRecord.setContracttype(dealercodeContract.getContractName());
                    boolean isParts = false ;
                    ProposalByCommericalAndMarketing approvedLimitAndConditionParts = new ProposalByCommericalAndMarketing();
                    approvedLimitAndConditionParts.setInstanceId(instanceId);
                    approvedLimitAndConditionParts.setDealername(applac.getDealername());
                    approvedLimitAndConditionParts.setSector("PEUGEOT");
                    approvedLimitAndConditionParts.setLimitType("Part");
                    List<ProposalByCommericalAndMarketing> approvedLimitAndConditionsParts = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndConditionParts);
                    if(dealercodeContract.getLimitType().toUpperCase().equals("PART") || (dealercodeContract.getLimitType().equals("Normal") &&  StringUtils.isNotEmpty(approvedLimitAndConditionsParts) && StringUtils.isNotNull(approvedLimitAndConditionsParts.get(0).getProposalLimit()) && approvedLimitAndConditionsParts.get(0).getProposalLimit() > 0 )){
                        //插入parts的值
                        isParts = true ;
                        contractRecord.setPartsAmount(approvedLimitAndConditionsParts.get(0).getProposalLimit().toString());
                        contractRecord.setPartsDepositRatio(approvedLimitAndConditionsParts.get(0).getProposalCashDeposit().toString());
                    }else{
                        if(dealercodeContract.getLimitType().equals("Normal")){
                            contractRecord.setPartsAmount("/");
                            contractRecord.setPartsDepositRatio("/");
                        }
                    }
                    contractRecord.setLimitType(dealercodeContract.getLimitType());
                    contractRecord.setDealercode(applac.getDealerCode());
                    contractRecord.setDealername(applac.getDealername());
                    String outDeposit ="";
                    ProposalByCommericalAndMarketing proposalByCommericalAndMarketingone = new ProposalByCommericalAndMarketing();
                    proposalByCommericalAndMarketingone.setDealername(applac.getDealername());
                    proposalByCommericalAndMarketingone.setSector(bc.getSector());
                    proposalByCommericalAndMarketingone.setLimitType(bc.getLimittype());
                    proposalByCommericalAndMarketingone.setInstanceId(instanceId);
                    List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketings = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(proposalByCommericalAndMarketingone);
                    if(StringUtils.isNotEmpty(proposalByCommericalAndMarketings)) {
                        if (StringUtils.isNotNull(proposalByCommericalAndMarketings.get(0).getProposalCashDeposit()) && !proposalByCommericalAndMarketings.get(0).getProposalCashDeposit().equals("")) {
                            contractRecord.setDeposit(proposalByCommericalAndMarketings.get(0).getProposalCashDeposit());
                        }
                        if (StringUtils.isNotNull(proposalByCommericalAndMarketings.get(0).getProposalCashDeposit()) && !proposalByCommericalAndMarketings.get(0).getApprovedCashDeposit().equals("")) {
                            outDeposit = proposalByCommericalAndMarketings.get(0).getApprovedCashDeposit();
                        }
                    }
                    contractRecord.setInstanceid(instanceId);
                    // contractRecord.setIssuedate(new Date());
                    Long sumFacilityamount =0L;
                    Long outSumFacilityamount =0L;
                    if(bc.getSector().contains("Naveco") ||bc.getSector().contains("NAVECO")){
                        if(bc.getLimittype().equals("NORMAL") ||bc.getLimittype().equals("Normal")) {
                            ProposalByCommericalAndMarketing approvedLimitAndConditionTemp = new ProposalByCommericalAndMarketing();
                            approvedLimitAndConditionTemp.setInstanceId(instanceId);
                            approvedLimitAndConditionTemp.setDealername(applac.getDealername());
                            approvedLimitAndConditionTemp.setSector(bc.getSector());
                            List<ProposalByCommericalAndMarketing> approvedLimitAndConditionTemps = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndConditionTemp);
                            for (ProposalByCommericalAndMarketing limitAndConditionTemp : approvedLimitAndConditionTemps) {
                                if(limitAndConditionTemp.getLimitType()!=null && limitAndConditionTemp.getLimitType().equals("NORMAL")){
                                    if(limitAndConditionTemp.getProposalLimit()!=null){
                                        sumFacilityamount = sumFacilityamount+limitAndConditionTemp.getProposalLimit();
                                    }
                                    if(limitAndConditionTemp.getApprovedLimit()!=null){
                                        outSumFacilityamount = outSumFacilityamount+limitAndConditionTemp.getApprovedLimit();
                                    }
                                }
                                if(limitAndConditionTemp.getLimitType()!=null && limitAndConditionTemp.getLimitType().equals("CB")){
                                    if(limitAndConditionTemp.getProposalLimit()!=null){
                                        sumFacilityamount = sumFacilityamount+limitAndConditionTemp.getProposalLimit();
                                    }
                                    if(limitAndConditionTemp.getApprovedLimit()!=null){
                                        outSumFacilityamount = outSumFacilityamount+limitAndConditionTemp.getApprovedLimit();
                                    }
                                }
                            }
                        }else{
                            ProposalByCommericalAndMarketing approvedLimitAndConditionTemp = new ProposalByCommericalAndMarketing();
                            approvedLimitAndConditionTemp.setInstanceId(instanceId);
                            approvedLimitAndConditionTemp.setDealername(applac.getDealername());
                            approvedLimitAndConditionTemp.setSector(bc.getSector());
                            approvedLimitAndConditionTemp.setLimitType(dealercodeContract.getLimitType());
                            List<ProposalByCommericalAndMarketing> approvedLimitAndConditionTemps = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndConditionTemp);
                            if(approvedLimitAndConditionTemps!=null && approvedLimitAndConditionTemps.size()>0 ){
                                ProposalByCommericalAndMarketing proposalByCommericalAndMarketing = approvedLimitAndConditionTemps.get(0);
                                if(proposalByCommericalAndMarketing!=null && proposalByCommericalAndMarketing.getProposalLimit()!=null){
                                    sumFacilityamount = sumFacilityamount+proposalByCommericalAndMarketing.getProposalLimit();
                                }
                                if(proposalByCommericalAndMarketing!=null && proposalByCommericalAndMarketing.getApprovedLimit()!=null){
                                    outSumFacilityamount = outSumFacilityamount+proposalByCommericalAndMarketing.getApprovedLimit();
                                }
                            }
                        }
                    }else{
                        ProposalByCommericalAndMarketing approvedLimitAndConditionTemp = new ProposalByCommericalAndMarketing();
                        approvedLimitAndConditionTemp.setInstanceId(instanceId);
                        approvedLimitAndConditionTemp.setDealername(applac.getDealername());
                        approvedLimitAndConditionTemp.setSector(bc.getSector());
                        approvedLimitAndConditionTemp.setLimitType(dealercodeContract.getLimitType());
                        List<ProposalByCommericalAndMarketing> approvedLimitAndConditionTemps = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(approvedLimitAndConditionTemp);
                        if(approvedLimitAndConditionTemps!=null && approvedLimitAndConditionTemps.size()>0 ){
                            ProposalByCommericalAndMarketing proposalByCommericalAndMarketing = approvedLimitAndConditionTemps.get(0);
                            if(proposalByCommericalAndMarketing!=null && proposalByCommericalAndMarketing.getProposalLimit()!=null){
                                sumFacilityamount = sumFacilityamount+proposalByCommericalAndMarketing.getProposalLimit();
                            }
                            if(proposalByCommericalAndMarketing!=null && proposalByCommericalAndMarketing.getApprovedLimit()!=null){
                                outSumFacilityamount = outSumFacilityamount+proposalByCommericalAndMarketing.getApprovedLimit();
                            }
                        }
                    }
                    if(StringUtils.isNotNull(sumFacilityamount)){
                        contractRecord.setFacilityamount(sumFacilityamount.toString());
                    }
                    contractRecord.setContractno(dealercodeContract.getContract());

                    CreditCondition creditCondition = new CreditCondition();
                    creditCondition.setDealername(applac.getDealername());
                    creditCondition.setSector(bc.getSector());
                    creditCondition.setLimittype(dealercodeContract.getLimitType());
                    creditCondition.setInstanceid(instanceId);
                    List<CreditCondition> creditConditions = creditConditionMapper.selectCreditConditionList(creditCondition);
                    if(creditConditions!=null && creditConditions.size()>0){
                        CreditCondition creditCondition1 = creditConditions.get(0);
                        if(creditCondition1!=null && creditCondition1.getExpireddate()!=null){
                            contractRecord.setExpirydate(creditCondition1.getExpireddate());
                        }
                    }
                    //查询
                    StringBuilder stringBuilderPersonal = new StringBuilder();
                    StringBuilder stringBuilderCompany = new StringBuilder();

                    for (Securities securitiesTemp : securitiesList) {
                        if(null != securitiesTemp.getGuaranteeType()){
                            if(securitiesTemp.getGuaranteeType().equals("personal")){
                                if(securitiesTemp.getProposalNameCN()!=null){
                                    stringBuilderPersonal.append(securitiesTemp.getProposalNameCN()).append(",");
                                }
                            }
                            if(securitiesTemp.getGuaranteeType().equals("corporate")){
                                if(securitiesTemp.getProposalNameCN()!=null){
                                    stringBuilderCompany.append(securitiesTemp.getProposalNameCN()).append(",");
                                }
                            }
                        }

                    }
                    if (!StringUtils.isEmpty(stringBuilderPersonal)) {
                        stringBuilderPersonal.deleteCharAt(stringBuilderPersonal.length() - 1);
                    }
                    if (!StringUtils.isEmpty(stringBuilderCompany)) {
                        stringBuilderCompany.deleteCharAt(stringBuilderCompany.length() - 1);
                    }
                    contractRecord.setPersonalguarantee(stringBuilderPersonal.toString());
                    contractRecord.setCompanyguarantee(stringBuilderCompany.toString());
                    String dictLabel = dictDataMapper.selectDictLabel("h_basic_contract_priority", dealercodeContract.getPriority());
                    contractRecord.setScenario(dictLabel);
                    BasicInformation basicInformation = new BasicInformation();
                    basicInformation.setInstanceId(instanceId);
                    basicInformation.setDealerNameCN(applac.getDealername());
                    List<BasicInformation> basicInformations = basicInformationService.selectBasicInformationList(basicInformation);
                    if(!StringUtils.isEmpty(basicInformations)){
                        BasicInformation basicInformation1 = basicInformations.get(0);
                        contractRecord.setGroupName(basicInformation1.getGroupNameEN());
                    }
                    DealerInformation dealerInfo = new DealerInformation();
                    dealerInfo.setDealerName(applac.getDealername());
                    dealerInfo.setMake(bc.getSector());
                    dealerInfo.setDealerCode(applac.getDealerCode());
                    List<DealerInformation> dealerInformationsnew = dealerInformationMapper.selectDealerInformationList(dealerInfo);
                    if(CollectionUtil.isNotEmpty(dealerInformationsnew)){
                        contractRecord.setOemdealercode(dealerInformationsnew.get(0).getDealerCodeFromManufacturer());
                    }
                   /* BigDecimal bigDecimal = new BigDecimal(outSumFacilityamount);
                    String amt ="";
                    String amt2 ="";*/
                    /*if(!StringUtils.isEmpty(outDeposit)){
                        String replace = outDeposit.replace("%", "");
                        BigDecimal bigDecimal1 = bigDecimal.multiply(new BigDecimal(replace)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal bigDecimal2 = bigDecimal1.divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        amt = bigDecimal2.toString();
                    }*/
                   /* if(!StringUtils.isEmpty(contractRecord.getDeposit())){
                        BigDecimal bigDecimal2 = new BigDecimal(contractRecord.getFacilityamount());
                        String replace2 = contractRecord.getDeposit().replace("%", "");
                        BigDecimal bigDecimal3 = bigDecimal2.multiply(new BigDecimal(replace2)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal bigDecimal4 = bigDecimal3.divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        amt2 = bigDecimal4.toString();
                    }*/
                    String note ="";
                    try{
                        if(Long.valueOf(contractRecord.getFacilityamount())>outSumFacilityamount){
                            note =  outSumFacilityamount+","+contractRecord.getFacilityamount();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    contractRecord.setNote(note);
                    contractRecordSerivce.insertContractRecord(contractRecord);
                    //插入报表3
                    contractRecordSerivce.insertContractRecordThree(contractRecord);
                    annualReviewyService.saveDbLog("1","新增合同报表",null,instanceId,null,contractRecord,"CRO确认");
                }


            }
        }
//        return list;
//        list.add(objectObjectHashMap);
        System.out.println("生成合同数据结束");
        return  1;
    }

    /**
     * 生成001的编号
     *
     * @param maxNum 最大数
     * @param count  累计的
     * @return
     */
    public static String sequenceCode(Long maxNum, Long count) {
        String strNum = String.valueOf(maxNum + count);
        if (StringUtils.isEmpty(strNum) || 1 >= strNum.length()) {
            return "";
        }
        return strNum.substring(1);
    }

    /**
     * 获取流程下对应得dealercode
     */
    public String dealercodelist(String instanceId,String dealerNameCN,String sector) {
        BasicInformation basicInformation = new BasicInformation();
        basicInformation.setInstanceId(instanceId);
        basicInformation.setDealerNameCN(dealerNameCN);
        List<BasicInformation> basicInformations = basicInformationService.selectBasicInformationList(basicInformation);
        if(StringUtils.isEmpty(basicInformations)){
            throw new BaseException("BasicInformation没对应得数据");
        }
        BasicInformation basicInformation1 = basicInformations.get(0);
        String sector1 = basicInformation1.getSector();
        String dealerCodeFromWFS = basicInformation1.getDealerCodeFromWFS();
        if(sector1.contains(",")){
            String[] split = sector1.split(",");
            String[] splits = dealerCodeFromWFS.split(",");
            String dealercode = "";
            for (int i = 0; i <split.length ; i++) {
                if(split[i].equals(sector)){
                    for (int j = 0; j <splits.length ; j++) {
                        dealercode = splits[i];
                    }
                }
            }
            String strip = StringUtils.strip(dealercode, "[]");
            return strip;
        }else {
            if(sector1.equals(sector)){
                String strip = StringUtils.strip(dealerCodeFromWFS, "[]");
                return strip;
            }
        }
        return "";
    }

    /**
     * 有历史合同情况下根据历史合同只需修改后面的编号，出合同序列信息
     */
    public String maincontractnoFormer (String dealercode,String letter,String instanceId,String yearMonth,String bianhao,String zimu,String contractname,String count){

        //修改后的合同号规则拼接
        if(StringUtils.isEmpty(count)){
            String contrctcode = dealercode+letter+yearMonth+bianhao+zimu;
            return contrctcode;
        }else {
            String contrctcode = dealercode+letter+yearMonth+bianhao+zimu+"-"+count;
            return contrctcode;
        }
    }

    public static Integer NameSort(String NameSort,String limitType){
        if(NameSort.equals("面签承诺函") && limitType.equals("Normal")){
            return 10;
        }else if (NameSort.equals("承诺函")){
            return 2;
        }else if (NameSort.equals("面签承诺函")  && limitType.equals("Demo")) {
            return 1;
        }else if (NameSort.equals("试乘试驾车抵押合同")){
            return 3;
        }else if (NameSort.equals("试乘试驾车贷款合同附件三")){
            return 4;
        }else if (NameSort.equals("试乘试驾车贷款合同附件二")){
            return 5;
        }else if (NameSort.equals("试乘试驾车贷款合同附件一")){
            return 6;
        }else if (NameSort.equals("试乘试驾车贷款合同")){
            return 7;
        }else if (NameSort.equals("试驾车企业保函")){
            return 8;
        }else if (NameSort.equals("试驾车个人保函")){
            return 9;
        }else if (NameSort.equals("人民币循环贷款协议补充协议-二网服务费")){
            return 11;
        }else if (NameSort.equals("三方-E")){
            return 12;
        }else if (NameSort.equals("三方-C")){
            return 13;
        }else if (NameSort.equals("三方合同-附件二 贷款额度及保证金通知书")){
            return 14;
        }else if (NameSort.equals("三方合同")){
            return 15;
        }else if (NameSort.equals("浮动抵押")){
            return 16;
        }else if (NameSort.equals("主信托")){
            return 17;
        }else if (NameSort.equals("人民币循环贷款合同附件五")){
            return 18;
        }else if (NameSort.equals("人民币循环贷款合同附件四")){
            return 19;
        }else if (NameSort.equals("人民币循环贷款合同附件三")){
            return 20;
        }else if (NameSort.equals("人民币循环贷款合同附件二")){
            return 21;
        }else if (NameSort.equals("人民币循环贷款合同")){
            return 22;
        }else if (NameSort.equals("企业保函")){
            return 23;
        }else if (NameSort.equals("个人保函")){
            return 24;
        }
        return 1;
    }

    /**
     * 没有历史合同的情况下拼新主合同号
     */
    public String maincontractno (String dealercode,String letter,String instanceId,String bianhao,String zimu,String contractname,String count) {
//        DealercodeCount dealercodeCount = new DealercodeCount();
//        dealercodeCount.setDealercode(dealercode);
//        dealercodeCount.setTemp(letter);
////        dealercodeCount.setInstanceid(instanceId);
//        dealercodeCount.setContractname(contractname);
//        List<DealercodeCount> dealercodeCounts = dealercodeCountService.selectDealercodeCountList(dealercodeCount);
//        if(StringUtils.isEmpty(dealercodeCounts)){
//            dealercodeCount.setCount((long) 1);
//            dealercodeCountService.insertDealercodeCount(dealercodeCount);//不存在就给个初始值
//        }else {
//            DealercodeCount dealercodeCount1 = dealercodeCounts.get(0);
//            dealercodeCount1.setCount(dealercodeCount1.getCount()+1);
//            dealercodeCountService.updateDealercodeCount(dealercodeCount1);//存在就加个1
//        }

        //拼人民币循环贷款主合同号
        String year = new SimpleDateFormat("yy", Locale.CHINESE).format(new Date());
//        String month = new SimpleDateFormat("M", Locale.CHINESE).format(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        String dateNowStr = sdf.format(new Date());
        LocalDate localDate = LocalDate.now();
        Month month1 = localDate.getMonth();
        String month2 = month1.getDisplayName(TextStyle.SHORT, Locale.ENGLISH);
        String month = month2.toUpperCase();
//        try {
//            month = new SimpleDateFormat("MMMMM", Locale.ENGLISH).format((new SimpleDateFormat("MM")).parse(month));
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        DealercodeCount dealercodeCount1 = dealercodeCountService.selectDealercodeCountList(dealercodeCount).get(0);
//        Long count = dealercodeCount1.getCount();
//        String code = sequenceCode((long) 1000, count);

            //修改后的合同号规则拼接
            if(StringUtils.isEmpty(count)){
                String contrctcode = dealercode+letter+year+month+bianhao+zimu;
                return contrctcode;
            }else {
                String contrctcode = dealercode+letter+year+month+bianhao+zimu+"-"+count;
                return contrctcode;
            }
        }
//        else {
//            Integer aa =1;
//            Long serialNumber =  aa.longValue();
//            String codes = sequenceCode((long) 1000, serialNumber);
//            if(contractname.equals("人民币循环贷款合同附件五")){
//                String contrctcode = dealercode+letter+year+month+codes+zimu+"-1";
//                return contrctcode;
//            }
//            //修改后的合同号规则拼接
//            if(count==1){
//                String contrctcode = dealercode+letter+year+month+codes+zimu;
//                return contrctcode;
//            }else {
//                String contrctcode = dealercode+letter+year+month+codes+zimu+"-"+count;
//                return contrctcode;
//            }
//        }
        //用完这个字段开始自增，并且自增后的值如果超过999就从1重新开始,或者当日期为一月一日时也从1开始计算
//        BeanUtil.copyProperties(dealercodeCount1,dealercodeCount);
//        if(count+1>999 || dateNowStr.equals("01-01")){
//            dealercodeCount.setCount((long)1);
//        }else {
//
//            dealercodeCount.setCount(count+1);
//        }
//        dealercodeCountService.updateDealercodeCount(dealercodeCount);
        //TODO 用变量
//        String contrctcode = dealercode+letter+year+month+code;





}
